Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all occurrences of a String using StringBuilder?

Tags:

java

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?

like image 425
meteoritepanama Avatar asked Aug 12 '10 22:08

meteoritepanama


People also ask

How do you replace a String in a String builder?

replace() method replaces the characters in a substring of this sequence with characters in the specified String. The substring begins at the specified start and extends to the character at index end - 1 or to the end of the sequence if no such character exists.

How do you replace multiple occurrences of a String in Java?

You can replace all occurrence of a single character, or a substring of a given String in Java using the replaceAll() method of java. lang. String class. This method also allows you to specify the target substring using the regular expression, which means you can use this to remove all white space from String.

What is the difference between Replace () and replaceAll ()?

The replaceAll() method is similar to the String. replaceFirst() method. The only difference between them is that it replaces the sub-string with the given string for all the occurrences present in the string.


1 Answers

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.

like image 123
Jon Skeet Avatar answered Sep 24 '22 14:09

Jon Skeet