.replace()

Christine_Yang's avatar
Published Aug 22, 2022Updated Aug 22, 2022
Contribute to Docs

The .replace() method switches a substring in a StringBuilder with a specified String and returns the modified object.

Syntax

myStringBuilder.replace(start, end, str);

Where start and end are the zero-based indices of the characters being replaced. The last character replaced is at end - 1, or the end of the sequence if end exceeds the length of the sequence. The characters are removed and the String str is inserted at start, the sequence lengthening if needed. If start is negative, greater than the end, or greater than the length of the sequence then a StringIndexOutOfBoundsException is thrown.

Example

The following example creates a StringBuilder with a specified String and then uses the .replace() method to change its contents:

import java.util.*;
public class Example {
public static void main(String[] args)
{
StringBuilder str = new StringBuilder("Hello World!");
System.out.println(str.toString());
str.replace(6,11,"Goodbye");
System.out.println(str.toString());
}
}

This produces the following output:

Hello World!
Hello Goodbye!

All contributors

Contribute to Docs

Learn Java on Codecademy