How do you use the replace method in StringBuffer?
The replace method in the StringBuffer class is used to replace characters at a specified position with new characters or strings. Its method signature is as follows:
public StringBuffer replace(int start, int end, String str)
Explanation of parameters:
- Start: the position to be replaced (including the character at that position)
- end: the position at which to end (excluding the character at that position)
- str: the new string to be substituted with
The example code is shown below:
StringBuffer sb = new StringBuffer("Hello World");
sb.replace(6, 11, "Java");
System.out.println(sb); // 输出结果为:Hello Java
In the given example, we replaced the characters in positions 6 to 11 (not including position 11) of the string “Hello World” with “Java”. The final output is “Hello Java”.
It is important to note that the replace method will modify the original StringBuffer object and return the newly replaced string.