Way2Java

delete() StringBuffer Example

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:
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);
 }
}



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.