StringBuilder deleteCharAt() in Java with Examples (original) (raw)
Last Updated : 29 Jun, 2022
The deleteCharAt(int index) method of StringBuilder class remove the character at the given index from String contained by StringBuilder. This method takes index as a parameter which represents the index of char we want to remove and returns the remaining String as StringBuilder Object. This StringBuilder is shortened by one char after application of this method. Syntax:
public StringBuilder deleteCharAt(int index)
Parameters: This method accepts one parameter index represents index of the character you want to remove. Return Value: This method returns this StringBuilder object after removing the character. Exception: This method throws StringIndexOutOfBoundsException if the index is less than zero, or index is larger than the length of String. Below programs demonstrate the deleteCharAt() method of StringBuilder Class: Example 1:
Java
class
GFG {
`` public
static
void
main(String[] args)
`` {
`` StringBuilder
`` str
`` =
new
StringBuilder("WelcomeGeeks");
`` System.out.println("Before removal String = "
`` + str.toString());
`` StringBuilder afterRemoval = str.deleteCharAt(
8
);
`` System.out.println("After removal of character"
`` + " at index
8
= "
`` + afterRemoval.toString());
`` }
}
Output:
Before removal String = WelcomeGeeks After removal of character at index 8 = WelcomeGeks
Example 2:
Java
class
GFG {
`` public
static
void
main(String[] args)
`` {
`` StringBuilder
`` str
`` =
new
StringBuilder("GeeksforGeeks");
`` System.out.println("Before removal String = "
`` + str.toString());
`` str = str.deleteCharAt(
3
);
`` System.out.println("After removal of Character"
`` + " from index=
3
"
`` + " String becomes => "
`` + str.toString());
`` str = str.deleteCharAt(
5
);
`` System.out.println("After removal of Character"
`` + " from index=
5
"
`` + " String becomes => "
`` + str.toString());
`` }
}
Output:
Before removal String = GeeksforGeeks After removal of Character from index=3 String becomes => GeesforGeeks After removal of Character from index=5 String becomes => GeesfrGeeks
Example 3: To demonstrate IndexOutOfBoundException
Java
class
GFG {
`` public
static
void
main(String[] args)
`` {
`` StringBuilder
`` str
`` =
new
StringBuilder("evil dead_01");
`` try
{
`` StringBuilder
`` afterRemoval
`` = str.deleteCharAt(
14
);
`` }
`` catch
(Exception e) {
`` System.out.println("Exception: " + e);
`` }
`` }
}
Output:
Exception: java.lang.StringIndexOutOfBoundsException: String index out of range: 14
Reference: https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#deleteCharAt(int)