StringBuilder delete() in Java

delete(): This method is available in java.lang.StringBuilder class of Java.

Syntax:

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

This method takes two arguments of type int as its parameters. This method removes 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.

Parameters: Two parameters are required for this method.

start: The beginning index, inclusive.

end: The ending index, exclusive.

Returns: This object.

Throws:

StringIndexOutOfBoundsException - if start is negative, greater than length(), or greater than the end.

For Example:

StringBuilder str = new StringBuilder("Hello World")

int start = 2, end = 7

str.delete(start,end) = > It returns Heorld.

Approach 1: When the index is in the range.

Java

public class Delete {
    public static void main(String[] args) {

        StringBuilder str = new StringBuilder("Hello World");

        int start = 2, end = 7;
        System.out.println(str.delete(start, end));
    }
}

Output:

Heorld


Approach 2: When the index is out of range.

Java

public class Delete {
    public static void main(String[] args) {

        StringBuilder str = new StringBuilder("Hello World");

        int start = 10, end = 7;
        System.out.println(str.delete(start, end));
    }
}


Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: start 10, end 7, length 11 at java.base/java.lang.AbstractStringBuilder.checkRangeSIOOBE(AbstractStringBuilder.java:1802) at java.base/java.lang.AbstractStringBuilder.delete(AbstractStringBuilder.java:912) at java.base/java.lang.StringBuilder.delete(StringBuilder.java:283)


No comments:

Post a Comment