0

I need to go something like:

public String func (String str){
    str = str.replace("aaa","bbb");
    str = str.replace("ccc","ddd");
    str = str.replace("eee","fff");
    return str;
}

Is there a more efficient way to do so? i guess that every replace function complexity is O(n), so three times calling replace will be O(3n). I am sure it is possible to be implemented in O(n), is there a simple way to do so with JAVA ??

(and an elegant way to do so with JAVA 8 in case the replacement input comes from a function like str.replace("aaa", getFirstReplacement()) ).

Gilo
  • 640
  • 3
  • 23
  • 4
    Note that `replace` returns a new String containing the results of the replacement. – Sotirios Delimanolis Jul 11 '16 at 17:02
  • 1
    http://stackoverflow.com/questions/1326682/java-replacing-multiple-different-substring-in-a-string-at-once-or-in-the-most may help – Wilson Jul 11 '16 at 17:04
  • In this case, you can replace the entire method body with `return str;`, that will do the same. – Holger Jul 11 '16 at 17:04
  • You could iterate over the string looking for occurrences strings you'd like to replace, then continually append to a string builder rather than creating new strings. – venture Jul 11 '16 at 17:18
  • Thanks Sotirios Delimanolis i edited – Gilo Jul 11 '16 at 18:38

0 Answers0