What is the purpose of the StringBuffer’s replace method?

The replace method of StringBuffer is used to replace characters or substrings in a string. Specifically, the replace method takes two parameters: a starting index and an ending index to specify the position of the characters or substrings to be replaced. It also takes a string as a parameter to specify the content to be replaced with.

Here is an example code using the replace method:

StringBuffer sb = new StringBuffer("Hello, World!");
sb.replace(7, 12, "Java");
System.out.println(sb.toString()); // 输出 "Hello, Java!"

In the example above, the replace method replaces the characters between indexes 7 and 12 in the string with “Java”, replacing “World” with “Java”.

It is important to note that the replace method of StringBuffer will modify the original string object instead of returning a new string object. Therefore, all references to the original string will reflect the replaced result.

bannerAds