StringBuilder.deleteCharAt()
Removes one character at an index. For a range there is delete(start, end).
Available since: Java 5
Syntax
public StringBuilder deleteCharAt(int index)Parameters
| Parameter | Type | Description |
|---|---|---|
| index | int | The index of the character to remove. |
Return value
StringBuilderThe same StringBuilder.
Examples
Removing a trailing separator:
void main() {
var sb = new StringBuilder();
for (int i = 1; i <= 3; i++) {
sb.append(i).append(',');
}
sb.deleteCharAt(sb.length() - 1);
IO.println(sb);
}Output:
1,2,3Removing a range with delete():
void main() {
var sb = new StringBuilder("Hello, cruel world");
sb.delete(5, 12);
IO.println(sb);
}Output:
Hello worldNotes
On an empty StringBuilder, deleteCharAt(sb.length() - 1) throws StringIndexOutOfBoundsException — check isEmpty() first. To clear everything, call sb.setLength(0).
See also
- StringBuilder.insert() — Inserts a value at the given position of a StringBuilder.
- StringBuilder — A mutable string: useful when text is built piece by piece, especially in a loop.
- StringBuilder.append() — Adds a value to the end of a StringBuilder.
Related recipes
In the tutorial
- StringBuilder — StringBuilder in Java: a mutable string, append, insert, reverse, deleteCharAt, call chains and building a string in a loop.