StringBuffer replace()


replace()

You can replace a set of characters with other sets in a StringBuffer object by calling replace(). The simplest form is shown here :

StringBuffer replace(int start, int end, String str)

Replacing strings The indexes are specified by start and end. Thus, the strings at the end of the start are replaced. The replacement string is passed to str. As a result, the StringBuffer object returns.

Example

Program
public class Main 
{
  public static void main(String[] args) 
  {
    StringBuffer sb = new StringBuffer("I am a good boy");
    System.out.println("Before replace = " + sb);
    System.out.println("After replace = " + sb.replace(7,11,"bad"));
  }
}

substring()

You can get a part of the StringBuffer by calling substring() method. It has the following two forms:

String substring(int start)
String substring(int start, int end)

The first form returns the substring that starts at the start and runs to the end of the invoking StringBuffer object. The second form returns the substring that starts at the start and runs through the end. These methods work just like those defined for String that were described earlier.