Skip to Content

Java StringBuffer delete remove character or clear content Example

  1. /*
  2.    Java StringBuffer delete remove character or clear content Example
  3.    This example shows how to delete or remove a particular character or clear
  4.    entire content of a StringBuffer object.
  5. */
  6.  
  7. public class JavaStringBufferDeleteExample {
  8.  
  9.   public static void main(String[] args) {
  10.     /*
  11.       Java StringBuffer class following methods to delete / remove characters
  12.       or claring the contents of a StringBuffer object.
  13.     */
  14.    
  15.     /*
  16.      StringBuffer delete(int start, int end) remove the characters from start
  17.      index to an end-1 index provided.
  18.      This method can throw a StringIndexOutOfBoundException if the start
  19.      index is invalid.
  20.     */
  21.     StringBuffer sb1 = new StringBuffer("Hello World");
  22.     sb1.delete(0,6);
  23.     System.out.println(sb1);
  24.    
  25.     /*
  26.      To clear contents of a StringBuffer use delete(int start, int end) method
  27.      in the below given way
  28.     */
  29.     StringBuffer sb2 = new StringBuffer("Some Content");
  30.     System.out.println(sb2);
  31.     sb2.delete(0, sb2.length());
  32.     System.out.println(sb2);
  33.    
  34.     /*
  35.      StringBuffer deleteCharAt(int index) deletes the character at specified
  36.      index.
  37.      This method throws StringIndexOutOfBoundException if index is negative
  38.      or grater than or equal to the length.
  39.     */
  40.     StringBuffer sb3 = new StringBuffer("Hello World");
  41.     sb3.deleteCharAt(0);
  42.     System.out.println(sb3);
  43.   }  
  44. }
  45.  
  46. /*
  47. Output would be
  48.  
  49. World
  50. Some Content
  51.  
  52. ello World
  53.  
  54. */