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.

package com.javatutorialhq.java.examples;

import java.util.Scanner;

/*
 * A java example source code to demonstrate
 * the use of delete() method of StringBuilder class
 */

public class StringBuilderDeleteExample {

	public static void main(String[] args) {

		// initialize the StringBuilder object
		StringBuilder sb = new StringBuilder("This is a test string");
		System.out.println("Current content:" + sb);

		// ask for the user input of begin index
		System.out.print("Please enter begin index:");
		Scanner s = new Scanner(System.in);
		Integer start = Integer.parseInt(s.nextLine());

		// ask for the user input of end index
		System.out.print("Please enter end index:");
		Integer end = Integer.parseInt(s.nextLine());
		s.close();
		sb.delete(start, end);
		// delete the character sequence specified by begin and end index
		System.out.println("New contents:" + sb);
	}
}

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