The deleteCharAt(int index) method of Java's StringBuilder class is used to remove a character at a specified position in a string. It modifies the original StringBuilder, reduces its length by one, and returns the same object.
The method throws a StringIndexOutOfBoundsException if the index is invalid (less than 0 or greater than or equal to the string length). This is useful for efficiently editing strings without creating new string objects.
Example:
class GFG {
public static void main(String[] args) {
StringBuilder str = new StringBuilder("WelcomeGeeks");
System.out.println("Before removal String = " + str);
str.deleteCharAt(8);
System.out.println("After removal at index 8 = " + str);
}
}
Output
Before removal String = WelcomeGeeks After removal at index 8 = WelcomeGeks
Explanation:
- A StringBuilder object str is created with the value "WelcomeGeeks".
- The deleteCharAt(8) method removes the character at index 8 ('e').
Syntax
public StringBuilder deleteCharAt(int index)
- Parameters: index – the position of the character to remove (0-based).
- Return Value: Returns the same StringBuilder object after removing the character.
Example 1:This code demonstrates how to use StringBuilder.deleteCharAt() in Java to remove specific characters from a string by index, updating the original string dynamically.
class GFG {
public static void main(String[] args) {
StringBuilder str = new StringBuilder("GeeksforGeeks");
System.out.println("Before removal String = " + str);
str.deleteCharAt(3);
System.out.println("After removal from index 3 = " + str);
str.deleteCharAt(5);
System.out.println("After removal from index 5 = " + str);
}
}
Output
Before removal String = GeeksforGeeks After removal from index 3 = GeesforGeeks After removal from index 5 = GeesfrGeeks
Explanation:
- A StringBuilder object str is initialized with "GeeksforGeeks".
- deleteCharAt(3) removes the character at index 3 ('k'), and the updated string is printed.
- deleteCharAt(5) removes the character at index 5 ('f' after the previous removal), and the final string is printed.
Example 2: This code demonstrates how StringBuilder.deleteCharAt() throws a StringIndexOutOfBoundsException when an invalid index is specified, and how to handle it using a try-catch block.
class GFG {
public static void main(String[] args) {
StringBuilder str = new StringBuilder("evil dead_01");
try {
str.deleteCharAt(14);
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}
Output
Exception: java.lang.StringIndexOutOfBoundsException: Index 14 out of bounds for length 12
Explanation:
- A StringBuilder object str is created with the string "evil dead_01".
- str.deleteCharAt(14): tries to remove a character at index 14, which is beyond the string length.
- This causes a StringIndexOutOfBoundsException.
- The try-catch block catches the exception and prints it, preventing the program from crashing.