Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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

ParameterTypeDescription
indexintThe 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,3

Removing a range with delete():

void main() {
    var sb = new StringBuilder("Hello, cruel world");
    sb.delete(5, 12);
    IO.println(sb);
}

Output:

Hello world

Notes

On an empty StringBuilder, deleteCharAt(sb.length() - 1) throws StringIndexOutOfBoundsException — check isEmpty() first. To clear everything, call sb.setLength(0).

See also

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.

Thanks for reading!

Donate to the site — we work hard for you.