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 indexs 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.
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:
Before removal String = WelcomeGeeks After removal String = Weeeks
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
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.