Using StringBuffer to replace substrings
Similar to StringBuilder
, we can use StringBuffer
class to replace substrings in a more efficient way. The only difference is that StringBuffer
is thread-safe. Here's an example:
public class SubstringReplace {
public static void main(String[] args) {
String originalString = "the quick brown fox jumps over the lazy dog";
System.out.println("Original String: " + originalString);
// Using StringBuffer to replace substrings
StringBuffer stringBuffer = new StringBuffer(originalString);
stringBuffer.replace(0, 3, "a");
String newString = stringBuffer.toString();
System.out.println("New String: " + newString);
}
}
In the above example, we are using StringBuffer
class to replace the first 3 characters in the string with the letter a
.
To compile and run the code, use the same commands as in step 2.
This should produce the following output:
Original String: the quick brown fox jumps over the lazy dog
New String: a quick brown fox jumps over the lazy dog