Java.lang.StringBuilder.replace() Method
Description
The java.lang.StringBuilder.replace() method replaces the characters in a substring of this sequence with characters in the specified String. The substring begins at the specified start and extends to the character at index end - 1 or to the end of the sequence if no such character exists.
Declaration
Following is the declaration for java.lang.StringBuilder.replace() method
public StringBuilder replace(int start, int end, String str)
Parameters
start -- This is the beginning index, inclusive.
end -- This is the ending index, exclusive.
str -- This is the String that will replace previous contents.
Return Value
This method returns this object.
Exception
StringIndexOutOfBoundsException -- if start is negative, greater than length(), or greater than end.
Example
The following example shows the usage of java.lang.StringBuilder.replace() method.
package com.tutorialspoint;
import java.lang.*;
public class StringBuilderDemo {
public static void main(String[] args) {
StringBuilder str = new StringBuilder("Java Util Package");
System.out.println("string = " + str);
// replace substring from index 5 to index 9
str.replace(5, 9, "Lang");
// prints the StringBuilder after replacing
System.out.println("After replacing: " + str);
}
}
Let us compile and run the above program, this will produce the following result:
string = Java Util Package After replacing: Java Lang Package