In this tutorial, we will discuss Java StringBuilder replace() method with the help of examples.
Syntax of replace() method:
//replace substring from index 4 to 9 by given string "hello" //4 is inclusive and 9 is exclusive sb.replace(4, 9, "hello");
replace() Description
public StringBuilder replace(int start, int end, String str): Replace the substring starting from start
index till end
index with the given string str
.
replace() Parameters
The replace() method of Java StringBuilder class takes three parameters:
- start: Represents the start of substring that is going to be replaced.
- end: Represents the end of the substring that is going to be replaced.
- str: This string is going to replace the substring marked by
start
andend
index.
replace Return Value
- Returns a StringBuilder object that contains the new string after replacement.
This method throws StringIndexOutOfBounds
Exception, if any of the following condition occurs:
- start index < 0
- start index > length of the string
Example 1: Replacing a substring with another string
public class JavaExample { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Hello Guys"); System.out.println("Given String : "+sb); //replace the substring sb.replace(6, 10, "Friends"); System.out.println("String after replace: "+sb); } }
Output:
Example 2: When replace string is greater than original string
public class JavaExample { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Text"); System.out.println("Given String: "+sb); //replace string is greater than original string sb.replace(0, 4, "AnotherText"); System.out.println("String after replace: "+sb); } }
Output:
Example 3: When end index is greater than the length of string
public class JavaExample { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Hello"); System.out.println("Given String: "+sb); //end index is greater than original string length sb.replace(0, 100, "Hi"); System.out.println("String after replace: "+sb); } }
Output:
Example 4: when start index is negative
public class JavaExample { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Text"); //start index is negative sb.replace(-5, 10, "AnotherText"); System.out.println("String after replace: "+sb); } }