java.lang.StringBuilder delete(int start, int end)

Description

On this document we will be showing a java example on how to use the delete(int start, int end) method of StringBuilder Class. Basically the delete(int start, int end) method removes/delete the characters in a substring of this sequence. The substring begins at the specified start and extends to the character at index end – 1 or to the end of the sequence if no such character exists. If start is equal to end, no changes are made. Make a note that index starts at 0, so please remember it when using this method.

Notes:

  • A StringIndexOutOfBoundsException will be thrown by the delete() method if start is negative, greater than length(), or greater than end.

Method Syntax

public StringBuilder delete(int start, int end)

Method Argument

Data Type Parameter Description
int start the beginning index on which we would like to begin deleting characters on this sequence.
int end the ending index on which we would like to to delete the characters on this sequence.

Method Returns

The delete() method returns this object with the characters removed as specified by the start and end index.

Compatibility

Requires Java 1.5 and up

Java StringBuilder delete() Example

Below is a java code demonstrates the use of delete(int start, int end) method of StringBuilder class. The example presented might be simple however it shows the behavior of the delete() method.

The above java example source code demonstrates the use of delete() method of StringBuilder class. We simply declare a new StringBuilder object with initial contents of "This is a test string". The user where then asked for the start and end index to be delete. The result of the delete() method were then printed at the end of the code.

Sample Output

Below is the sample output when you run the above example.

StringBuilder delete() example output