3

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?

2 Answers 2

7

It's because you're getting index of "Line 2" as starting index, which is the beginning of that line, 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());
        }
}
Sign up to request clarification or add additional context in comments.

3 Comments

It works, but how if I don't know if the next string is Line 3?
builder.replace(builder.indexOf("Line 2"), builder.indexOf("Line 2") + "Line 2\n".length(), "Temporary Line\n");
Get the length of the string you want to replace, and add that value to the value returned by builder.indexOf("Line 2") (in this example). That will be your last index.
2
final String toReplace = "Line 2\n";
final int start = builder.indexOf(toReplace);
builder.replace(start, start+toReplace.length(), "Temporary Line\n");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.