delete() StringBuffer Example

December 9, 2014 | class StringBuffer
Deleting a group of characters with delete() StringBuffer

To manipulate string, java.lang.StringBuffer class comes with many methods, otherwise which will take long laborious coding as in C/C++. One such method is delete(int, int) that deletes a group of characters.

What Java API says of delete() StringBuffer:
  • public synchronized java.lang.StringBuffer delete(int startIndex, int endIndex): Deletes a group of characters from buffer starting from startIndex to endIndex-1. Throws StringIndexOutOfBoundsException if the argument index numbers are more than the buffer size.
Following delete() StringBuffer example illustrates the method.
public class Demo
{
  public static void main(String args[])
  {						
   StringBuffer sb1 = new StringBuffer("ABCDEFGHI");
   
   System.out.println("Original string buffer sb1 before delete: " + sb1);
   System.out.println("Number of characteres in sb1 before delete: " + sb1.length());  

   sb1.delete(2, 5);                   // deletes 2, 3, and 4 characters

   System.out.println("String buffer sb1 after calling delete(2, 5): " + sb1);  
   System.out.println("Number of characteres in sb1 after calling delete(2, 5): " + sb1.length());  

   sb1.delete(100, 200);
 }
}

delete() StringBuffer Output screenshot on delete() StringBuffer Example

sb1.delete(2, 5);

Deletes the characters with index numbers 2, 3 and 4. That is, 3 characters are deleted. We have seen earlier how to delete a single character in StringBuffer.

sb1.delete(100, 200);

Throws StringIndexOutOfBoundsException as 100 and 200 index numbers does not exist in StringBuffer object sb1.