The delete(int start, int end) method of StringBuilder class removes the characters starting from index start to index end-1 from String contained by StringBuilder. This method takes two indexes as a parameter first start represents index of the first character and endIndex represents index after the last character of the substring to be removed from String contained by StringBuilder and returns the remaining String as StringBuilder Object.
Syntax:
public StringBuilder delete(int start, int end)
Parameters: This method accepts two parameters:
- start: index of the first character of the substring.
- end: index after the last character of the substring.
Return Value: This method returns this StringBuilder object after removing the substring.
Exception: This method throws StringIndexOutOfBoundsException if the start is less than zero, or start is larger than the length of String, or start is larger than end.
Below programs demonstrate the delete() method of StringBuilder Class:
Example 1:
Java
class GFG {
public static void main(String[] args)
{
StringBuilder
str
= new StringBuilder( "WelcomeGeeks" );
System.out.println( "Before removal String = "
+ str.toString());
StringBuilder afterRemoval = str.delete( 2 , 8 );
System.out.println( "After removal String = "
+ afterRemoval.toString());
}
}
|
OutputBefore removal String = WelcomeGeeks
After removal String = Weeeks
Example 2:
Java
class GFG {
public static void main(String[] args)
{
StringBuilder
str
= new StringBuilder( "GeeksforGeeks" );
System.out.println( "Before removal String = "
+ str.toString());
StringBuilder afterRemoval = str.delete( 8 , 8 );
System.out.println( "After removal of SubString"
+ " start=8 to end=8"
+ " String becomes => "
+ afterRemoval.toString());
afterRemoval = str.delete( 1 , 8 );
System.out.println( "After removal of SubString"
+ " start=1 to end=8"
+ " String becomes => "
+ afterRemoval.toString());
}
}
|
Output: Before removal String = GeeksforGeeks
After removal of SubString start=8 to end=8 String becomes => GeeksforGeeks
After removal of SubString start=1 to end=8 String becomes => GGeeks
Example 3: To demonstrate IndexOutOfBoundException
Java
class GFG {
public static void main(String[] args)
{
StringBuilder
str
= new StringBuilder( "GeeksforGeeks" );
try {
StringBuilder afterRemoval = str.delete( 7 , 4 );
}
catch (Exception e) {
System.out.println( "Exception: " + e);
}
}
}
|
Output: Exception: java.lang.StringIndexOutOfBoundsException
Reference:
https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#delete(int, int)