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:

  • public synchronized java.lang.StringBuffer replace(int startIndex, int endIndex, String string1): Replaces a group of characters of string buffer from startIndex to endIndex-1 with string string1. Replaced number of characters in the buffer need not be equal to the length of string1. Throws StringIndexOutOfBoundsException if the argument more than buffer size.
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");
 }
}


replace() StringBuffer
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".

Leave a Comment

Your email address will not be published.