This is an off-by-one error. The first two parameters to replace(...) are the starting index of the substring to replace, inclusive, and the ending of the substring to replace, exclusive. By using the same value for both, you are in effect "replacing" the nothing between indexes 1 and 2. This inclusive/exclusive way of expressing a range is extremely common.
java - Replacing individual characters in a StringBuffer - Stack Overflow
java - How to use replaceAll() method in StringBuffer? - Stack Overflow
java - StringBuffer.replace javadoc - Stack Overflow
java - Replace all occurrences of a String using StringBuilder? - Stack Overflow
Videos
There is no such method on StringBuffer. Perhaps the following will help:
StringBuffer str1 = new StringBuffer("whatever");
// to get a String result:
String str2 = str1.toString().replaceAll(regex, substr);
// to get a StringBuffer result:
StringBuffer str3 = new StringBuffer(str2);
This solution is a bit more optimized, as it does not create new strings or string buffers. Suppose you want to replace str1 with str2.
StringBuffer strBuf = new StringBuffer("yourString");
int startIndex = strBuf.indexOf(str1);
while(startIndex != -1){
strBuf.replace(start, start + str1.length(), str2);
start = strBuf.indexOf(str1, start + str1.length());
}
With this method, you find the index of each occurance of str1 in your buffer and replace it one by one with str2. The method indexOf(String str, int index), returns the index of the first occurance of str starting from index.
Well, you can write a loop:
public static void replaceAll(StringBuilder builder, String from, String to) {
int index = builder.indexOf(from);
while (index != -1) {
builder.replace(index, index + from.length(), to);
index += to.length(); // Move to the end of the replacement
index = builder.indexOf(from, index);
}
}
Note that in some cases it may be faster to use lastIndexOf, working from the back. I suspect that's the case if you're replacing a long string with a short one - so when you get to the start, any replacements have less to copy. Anyway, this should give you a starting point.
You could use Pattern/Matcher. From the Matcher javadocs:
Pattern p = Pattern.compile("cat");
Matcher m = p.matcher("one cat two cats in the yard");
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "dog");
}
m.appendTail(sb);
System.out.println(sb.toString());
Is there a way to find and replace a substring inside a StringBuffer without creating a new String object? Java and dotnet have this. Could there be a pub.dev package anyone knows about?