I am trying to replace some string in StringBuilderwith a method replace, but unfortunately it works as a method insert.
Here is the 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());
}
}
Result for this code:
Line 1
Temporary Line
Line 2
Line 3
I want to:
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 as follows:
builder.replace(builder.indexOf("Line 2"), builder.indexOf("Line 3"), "Temporary Line\n");
But a new problem arises, what if the next line (for this example Line 3), I donβt know the content?
source
share