![]() |
VOOZH | about |
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.
Hello Java
Explanation:
public StringBuilder replace(int start, int end, String str)
Parameters: This method accepts three parameters:
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.
Example 1: Basic Replacement
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
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()
Java Programming
Explanation: When start and end are the same, the string is inserted at that position.
Example 4: Replacing Entire String
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
Output:
StringIndexOutOfBoundsException
Explanation: The end index exceeds the length of the StringBuilder.