2014-01-13 58 views
5

我需要在java中找到一個類似的光滑方式來做多字符串替換,你可以使用str_replace在php中執行此操作。在一個字符串中替換多個字符像java一樣的java 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()這個特殊的情況下,正則表達式,我不希望使用我覺得這是一個蠻力的方法來做到這一點:像這裏: How to replace multiple words in a single string in Java?

+4

檢查這個http://stackoverflow.com/questions/1326682/java-replacing-multiple-different-substring-in-a-string-at-once-or-in-the-most或者你可以嘗試使用Apache Commons StringUtils.replaceEach()http:/ /commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html – pomkine

+0

@pomkine - 我也看着這個解決方案,並想知道是否有另一種方法來做到這一點。 –

+0

在內部,'str_replace'遍歷數組...... Java也是如此。 – Stephan

回答

3

你可以做到這一點從StringUtils的replaceEach():

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" 
+0

接受這個答案,但也想給這個以及pomkine功勞。 –

+0

抱歉沒有注意到,pomkine更快:+1 @pomkine – treeno

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()); 
    } 
相關問題