deleteCharAt() StringBuffer Example

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 deleteCharAt() StringBufferthat deletes a single character.
What Java API says about deleteCharAt() StringBuffer:
  • public synchronized java.lang.StringBuffer deleteCharAt(int index1): Deletes a single character from buffer at index number index1. Throws StringIndexOutOfBoundsException if the argument is more than buffer size.

Following deleteCharAt() StringBuffer example illustrates.

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.deleteCharAt(2);                         // deletes char at index number 2

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

   sb1.deleteCharAt(100);
 }
}


deleteCharAt() StringBuffer
Output screenshot on deleteCharAt() StringBuffer Example

sb1.deleteCharAt(2);

Deletes the character at index number 2. That is, one character is deleted. We have seen earlier how to delete a group of characters.

sb1.deleteCharAt(100);

Throws StringIndexOutOfBoundsException as 100 index number does not exist in StringBuffer object sb1.

Another method exists with similar functionality delete() StringBuffer Example.

Pass your comments and suggestions for the improvement of this tutorial "deleteCharAt() StringBuffer Example".

Leave a Comment

Your email address will not be published.