The replace(int start, int end, String str) method of StringBuilder is used to replace a specified range of characters with a given string. It modifies the existing StringBuilder object directly, making it efficient for frequent updates to strings.
class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello World");
sb.replace(6, 11, "Java");
System.out.println(sb);
}
}
Output
Hello Java
Explanation:
- A StringBuilder object is created with the initial value "Hello World".
- The replace(6, 11, "Java") method replaces the characters from index 6 to 10 ("World") with "Java".
- The modified StringBuilder is printed, showing the updated string "Hello Java".
Syntax
public StringBuilder replace(int start, int end, String str)
Parameters: This method accepts three parameters:
- start - Starting index (inclusive)
- end - Ending index (exclusive)
- str - String to replace the specified range
Return Value: This method returns StringBuilder object after successful replacement of characters.
Note:
- The character at index start is included, while the character at index end is excluded.
- If start == end, the string is inserted at that position.
Examples of StringBuilder replace() Method
Example 1: Basic Replacement
class GFG {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("WelcomeGeeks");
System.out.println("Original: " + sb);
sb.replace(1, 7, "e are ");
System.out.println("After: " + sb);
}
}
Output
Original: WelcomeGeeks After: We are Geeks
Explanation: Characters from index 1 to 6 are replaced with "e are ".
Example 2: Replacing a Substring in the Middle
class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("I like Python");
sb.replace(7, 13, "Java");
System.out.println(sb);
}
}
Output
I like Java
Explanation: The replace(7, 13, "Java") call replaces the substring "Python" with "Java" in the middle of the StringBuilder.
Example 3: Inserting Using replace()
class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Programming");
sb.replace(0, 0, "Java ");
System.out.println(sb);
}
}
Output
Java Programming
Explanation: When start and end are the same, the string is inserted at that position.
Example 4: Replacing Entire String
class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Old Value");
sb.replace(0, sb.length(), "New Value");
System.out.println(sb);
}
}
Output
New Value
Explanation: It replaces all characters from index 0 to the length of the StringBuilder, effectively replacing the entire string with "New Value".
Example 5: Invalid Index Handling
class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Example");
sb.replace(3, 20, "Test");
}
}
Output:
StringIndexOutOfBoundsException
Explanation: The end index exceeds the length of the StringBuilder.