![]() |
VOOZH | about |
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:
Before removal String = WelcomeGeeks After removal at index 8 = WelcomeGeks
Explanation:
public StringBuilder deleteCharAt(int index)
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.
Before removal String = GeeksforGeeks After removal from index 3 = GeesforGeeks After removal from index 5 = GeesfrGeeks
Explanation:
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.
Exception: java.lang.StringIndexOutOfBoundsException: Index 14 out of bounds for length 12
Explanation: