Java StringBuilder deleteCharAt()方法及实例
StringBuilder类 的 deleteCharAt(int index) 方法从StringBuilder包含的字符串中删除给定索引处的字符。该方法将index作为参数,代表我们要删除的字符的索引,并将剩余的字符串作为StringBuilder对象返回。使用该方法后,这个StringBuilder缩短了一个字符。 语法
public StringBuilder deleteCharAt(int index)
参数: 该方法接受一个参数 index ,代表你要删除的字符的索引。
返回值: 该方法在删除字符后返回 这个StringBuilder对象 。
异常: 如果索引小于0,或者索引大于String的长度,该方法会抛出 StringIndexOutOfBoundsException 。下面的程序演示了StringBuilder类的deleteCharAt()方法:
例1 :
// Java program to demonstrate// the deleteCharAt() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder("WelcomeGeeks"); // print string System.out.println("Before removal String = " + str.toString()); // remove the Character from index 8 StringBuilder afterRemoval = str.deleteCharAt(8); // print string after removal of Character System.out.println("After removal of character" + " at index 8 = " + afterRemoval.toString()); }}
输出
Before removal String = WelcomeGeeksAfter removal of character at index 8 = WelcomeGeks
例2 :
// Java program to demonstrate// the deleteCharAt() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder("GeeksforGeeks"); // print string System.out.println("Before removal String = " + str.toString()); // remove the Character from index 3 str = str.deleteCharAt(3); // print string after removal of Character System.out.println("After removal of Character" + " from index=3" + " String becomes => " + str.toString()); // remove the substring from index 5 str = str.deleteCharAt(5); // print string after removal of Character System.out.println("After removal of Character" + " from index=5" + " String becomes => " + str.toString()); }}
输出
Before removal String = GeeksforGeeksAfter removal of Character from index=3 String becomes => GeesforGeeksAfter removal of Character from index=5 String becomes => GeesfrGeeks
例3: 演示IndexOutOfBoundException
// Java program to demonstrate// exception thrown by the deleteCharAt() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder("evil dead_01"); try { // make index > length of String StringBuilder afterRemoval = str.deleteCharAt(14); } catch (Exception e) { System.out.println("Exception: " + e); } }}输出
Exception: java.lang.StringIndexOutOfBoundsException: String index out of range: 14
**参考资料: ** https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#deleteCharAt(int)
