Delete or replace or reverse a StringBuffer

ReturnMethodSummary
StringBufferdelete(int start, int end)Removes the characters in a substring of this sequence.
StringBufferdeleteCharAt(int index)Removes the char at the specified position in this sequence.
StringBufferreplace(int start, int end, String str)Replaces the characters in a substring of this sequence with characters in the specified String.
StringBufferreverse()Causes this character sequence to be replaced by the reverse of the sequence.

public class Main {
  public static void main(String[] argv) {
    StringBuffer sb = new StringBuffer();
    sb.append(true);
    sb.append("java2s.com");
    
    sb.delete(1, 2);
    System.out.println(sb.toString());
  }
}

The output:


tuejava2s.com

public class Main {
  public static void main(String[] argv) {
    StringBuffer sb = new StringBuffer();
    sb.append("java2s.com");
    
    sb.reverse();
    System.out.println(sb.toString());
  }
}

The output:


moc.s2avaj

Here is a program that demonstrates the delete( ) and deleteCharAt( ) methods:

 
public class Main {
  public static void main(String args[]) {
    StringBuffer sb = new StringBuffer("This is a test.");

    sb.delete(4, 7);
    System.out.println("After delete: " + sb);

    sb.deleteCharAt(0);
    System.out.println("After deleteCharAt: " + sb);
  }
}

The following output is produced:


After delete: This a test.
After deleteCharAt: his a test.

The following program demonstrates replace( ):

 
public class Main {
  public static void main(String args[]) {
    StringBuffer sb = new StringBuffer("This is a test.");

    sb.replace(5, 7, "was");
    System.out.println("After replace: " + sb);
  }
}

Here is the output:


After replace: This was a test.
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.