Java StringBuilder replace() Method
Example
Replace "World" with "Java":
StringBuilder sb = new StringBuilder("Hello World");
sb.replace(6, 11, "Java");
System.out.println(sb);
Definition and Usage
The replace() method replaces the characters between two positions with new text.
The character at end is not replaced. The new text can be shorter or longer than the text it replaces.
Tip: Unlike the String replace() method, this method uses positions, not the text to search for.
Syntax
public StringBuilder replace(int start, int end, String str)
Parameter Values
| Parameter | Description |
|---|---|
| start | Required. The index of the first character to replace. |
| end | Required. The index after the last character to replace. |
| str | Required. The new text. |
Technical Details
| Returns: | The same StringBuilder, with the new text. |
|---|---|
| Throws: | StringIndexOutOfBoundsException - if start is negative, larger than the length, or larger than end. |
Related Pages
❮ StringBuilder Methods