Replace all occurrences of a String using StringBuilder?

Viewed 133414

Am I missing something, or does StringBuilder lack the same "replace all occurrences of a string A with string B" function that the normal String class does? The StringBuilder replace function isn't quite the same. Is there any way to this more efficiently without generating multiple Strings using the normal String class?

14 Answers

Even simple one is using the String ReplaceAll function itself. You can write it as

StringBuilder sb = new StringBuilder("Hi there, are you there?")
System.out.println(Pattern.compile("there").matcher(sb).replaceAll("niru"));

Kotlin Method

  fun replaceAllStringBuilder(
        builder: java.lang.StringBuilder,
        from: String,
        to: String
    ) {
        if (!builder.contains(from)||from.isNullOrEmpty()) return
        
            var index = builder.indexOf(from)
            while (index != -1) {
                builder.replace(index, index + from.length, to)
                index += to.length 
                index = builder.indexOf(from, index)
            }
        

    }
Related