.deleteCharAt()

The .deleteCharAt() method removes the character at the specified index from the contents of a StringBuilder and returns the modified object.

Syntax

myStringbuilder.deleteCharAt(index);

The int argument index specifies the zero-based index of the character to delete. The sequence is shortened by one character. If index is negative or greater than the length of the sequence, a StringIndexOutOfBoundsException is thrown.

Example

The following example creates a StringBuilder with a specified String then uses the .deleteCharAt() method to change its contents:

import java.util.*;
public class Example {
public static void main(String[] args)
{
StringBuilder str = new StringBuilder("Hello World!");
System.out.println(str.toString());
str.deleteCharAt(11);
System.out.println(str.toString());
}
}

This produces the following output:

Hello World!
Hello World

Contributors

Interested in helping build Docs? Read the Contribution Guide or share your thoughts in this feedback form.

Learn Java on Codecademy