I try to replace some string in StringBuilder using the replace method, but unfortunately it running like the insert method.
Here is some code:
public class StringBuilderReplace {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder();
builder.append("Line 1\n");
builder.append("Line 2\n");
builder.append("Line 3\n");
builder.replace(builder.indexOf("Line 2"), builder.indexOf("Line 2"), "Temporary Line\n");
System.out.println(builder.toString());
}
}
The result for this code:
Line 1
Temporary Line
Line 2
Line 3
What I want is:
Line 1
Temporary Line
Line 3
How to do this to get the result I want?
Update based on AljoshaBre answer
It works if I change the code like this one:
builder.replace(builder.indexOf("Line 2"), builder.indexOf("Line 3"), "Temporary Line\n");
But new problem occur, what if the next string (for this example Line 3) I don't know the content?