In this guide, we will discuss the Java StringBuilder deleteCharAt() method with examples.
Syntax of deleteCharAt() Method:
sb.deleteCharAt(3); //deletes char present at index 3
Here sb is an instance of StringBuilder class.
deleteCharAt() Description
public StringBuilder deleteCharAt(int index): This method deletes the character present at the specified index. The StringBuilder instance returned by this method is one char short in length.
deleteCharAt() Parameters
It takes a single parameter:
- index: An integer value that represents the index (position) of a character in the sequence. The character specified by this index is deleted.
deleteCharAt() Return Value
- Returns an instance of StringBuilder after deleting the specified character.
It throws StringIndexOutOfBoundsException, if any of the following condition occurs:
- If
index < 0 - If
index >= sb.length()
Example 1: Deleting first and last character
public class JavaExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("$Text$");
System.out.println("Sequence before delete: "+sb);
//deleting first char
sb.deleteCharAt(0);
//deleting last char
sb.deleteCharAt(sb.length()-1);
//print Sequence
System.out.println("Sequence after delete: "+sb);
}
}
Output:

Example 2: Delete last two characters
public class JavaExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Cool Text");
System.out.println("Sequence before delete: "+sb);
//deleting last two characters
sb.deleteCharAt(sb.length()-1);
sb.deleteCharAt(sb.length()-1);
//print Sequence
System.out.println("Sequence after delete: "+sb);
}
}
Output:

Example 3: Delete first two characters
public class JavaExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Text");
System.out.println("Given Sequence: "+sb);
//delete first two characters
sb.deleteCharAt(0);
sb.deleteCharAt(0);
System.out.println("Output Sequence: "+sb);
}
}
Output:

Example 4: If given index is negative
public class JavaExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Text");
sb.deleteCharAt(-1);
System.out.println(sb);
}
}
Output:
