How to use StringBuffer to replace specific characters.
To replace specific characters using StringBuffer, you can use the replace method of StringBuffer. This method takes two parameters, the first parameter is the starting index of the character to be replaced, and the second parameter is the ending index of the character to be replaced (excluding the ending index).
Here is an example:
StringBuffer sb = new StringBuffer("Hello World");
sb.replace(6, 11, "Java");
System.out.println(sb.toString()); // 输出:Hello Java
In this example, we start by creating a StringBuffer object with the content “Hello World”. Then we use the replace method to replace the characters between index 6 and index 11 with “Java”. Finally, we print out the modified string.
It is important to note that the replace method of StringBuffer will modify the original StringBuffer object instead of returning a new string. If you want to obtain a new string, you can call the toString method after the replace method.