replace():replace a StringBuffer

replace( ) can replace one set of characters with another set inside a StringBuffer.

StringBuffer replace(int start, int end, String str)
Replaces the characters in a substring of this sequence with characters in the specified String.

The substring being replaced is specified by the indexes startIndex and endIndex. substring at startIndex through endIndex-1 is replaced. The replacement string is passed in str. The resulting StringBuffer object is returned.

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.
Home 
  Java Book 
    Essential Classes  

StringBuffer:
  1. Create StringBuffer object
  2. append
  3. StringBuffer capacity()
  4. charAt(int index): get the char at specified index
  5. delete(int start, int end) and deleteCharAt(int index)
  6. ensureCapacity( )
  7. getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
  8. indexOf(String str)
  9. lastIndexOf(String str)
  10. StringBuffer length()
  11. Insert(): add data in the middle of a StringBuffer
  12. replace():replace a StringBuffer
  13. StringBuffer reverse()
  14. setCharAt(int index, char ch)
  15. setLength
  16. substring
  17. toString():Convert StringBuffer to String