StringBuilder will replace run method as insert method

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?

+3
source share
2 answers

This is because you get the β€œLine 2” index as the starting index, which is the beginning of this row, and you do the same for the last index.

I think you should do the following:

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");

            String lineToReplace = "Line 1\n";
            int startIndex = builder.indexOf(lineToReplace);
            int lastIndex = startIndex + lineToReplace.length();

            builder.replace(startIndex, lastIndex, "Temporary Line\n");
            System.out.println(builder.toString());
        }
}
+7
source
final String toReplace = "Line 2\n";
final int start = builder.indexOf(toReplace);
builder.replace(start, start+toReplace.length(), "Temporary Line\n");
+2
source

All Articles