Replace all occurrences of a String using StringBuilder?

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.

Leave a Comment