Way2Java

replace() StringBuffer Example

replace() StringBuffer Method

java.lang.StringBuffer class comes with many methods to manipulate string. replace() method replaces a group of characters in the buffer.

What Java API says about replace() StringBuffer:

Following replace() 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 replace: " + sb1);
   System.out.println("Number of characteres in sb1 before replace: " + sb1.length());  

   sb1.replace(3, 6, "123456");

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

   sb1.replace(100, 200, "hello");
 }
}



Output screen of replace() StringBuffer Example

sb1.replace(3, 6, "123456");

Replaces 3 characters with index numbers 3, 4 and 5 with string 123456 of length 6 characters. That is, 3 characters are repalced by 6 characters. We have seen earlier how to replace a single character.

sb1.replace(100, 200, "123456");

Throws StringIndexOutOfBoundsException as index numbers 100 and 200 do not exist in StringBuffer object sb1.

Pass your comments and suggestions for improvement on this tutorial "replace() StringBuffer Example".