5

I need to find a similar slick way in java to do multi string replace the same way you can do this in php with str_replace.

I want to take a string and then returns a string with the numbers 1 to 10 replaced with the word for those numbers.

"I won 7 of the 10 games and received 30 dollars." => "I won seven of the ten games and received 30 dollars."

In php, you can do:

function replaceNumbersWithWords($phrase) { 

  $numbers = array("1", "2", "3","4","5","6","7","8","9","10");
  $words   = array("one", "two", "three","four","five","six","seven","eight","nine","ten");
  return str_replace($numbers,$words,$phrase);

}

I'm not sure there is an elegant way to do regular expressions on this particular case with String.replace(), and I don't want to use what I feel is a brute force approach to do this: like here: How to replace multiple words in a single string in Java?.

Community
  • 1
  • 1
Kristy Welsh
  • 7,828
  • 12
  • 64
  • 106
  • 4
    check this http://stackoverflow.com/questions/1326682/java-replacing-multiple-different-substring-in-a-string-at-once-or-in-the-most or you can try to use Apache Commons StringUtils.replaceEach() http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html – pomkine Jan 13 '14 at 12:59
  • @pomkine - I looked at that solution as well and was wondering if there's yet another way to do this. – Kristy Welsh Jan 13 '14 at 13:01
  • Internally, `str_replace` iterates over the arrays... so does Java. – Stephan Jan 13 '14 at 13:10
  • possible duplicate of [How can I replace two strings in a way that one does not end up replacing the other?](http://stackoverflow.com/questions/26791441/how-can-i-replace-two-strings-in-a-way-that-one-does-not-end-up-replacing-the-ot) –  Nov 09 '14 at 11:04

2 Answers2

3

Maybe you can replace like this:

    Map<String, String> replaceMap = new HashMap<String, String>();
    replaceMap.put("1","one");
    replaceMap.put("2","two");
    replaceMap.put("3","three");
    replaceMap.put("4","four");
    String str = "aaa1ss2";
    for (Map.Entry<String, String> entry : replaceMap.entrySet()) {
        str = str.replaceAll(entry.getKey(), entry.getValue());
    }
lichengwu
  • 4,277
  • 6
  • 29
  • 42
3

You can do that with replaceEach() from StringUtils:

http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#replaceEach(java.lang.String, java.lang.String[], java.lang.String[])

StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"})  = "wcte"
treeno
  • 2,510
  • 1
  • 20
  • 36