在Java中如何替换字符串中的多个单词,类似于PHP中的str_replace函数。

5

我需要在Java中找到一种类似于php中的str_replace的多字符串替换方法。

我想把一个字符串中的1到10数字替换为这些数字的单词。

"我赢得了10场比赛中的7场,并获得了30美元。" => "我赢得了十场比赛中的七场,并获得了30美元。"

在php中,可以使用以下代码:

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);

}

我不确定有一种优雅的方法可以使用String.replace()对这个特定情况进行正则表达式,而且我不想使用我觉得是一种蛮力方法来做这个:像这里一样: 如何在Java中替换单个字符串中的多个单词?


4
请查看此网址:https://dev59.com/JnM_5IYBdhLWcg3wjj-r 或者您可以尝试使用Apache Commons StringUtils.replaceEach()方法。http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html - pomkine
@pomkine - 我也看了那个解决方案,不知道还有没有其他方法可以做到这一点。 - Kristy Welsh
在内部,“str_replace”遍历数组……Java也是如此。 - Stephan
2个回答

3
也许您可以像这样进行替换:
    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());
    }

3

接受这个答案,但也想给pomkine以荣誉。 - Kristy Welsh
抱歉没有注意到,pomkine更快:+1 @pomkine - treeno

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接