假设我有以下代码:
String word1 = "bar";
String word2 = "foo";
String story = "Once upon a time, there was a foo and a bar."
story = story.replace("foo", word1);
story = story.replace("bar", word2);
运行此代码后,story
的值将为"Once upon a time, there was a foo and a foo."
如果我以相反的顺序替换它们,也会出现类似的问题:
String word1 = "bar";
String word2 = "foo";
String story = "Once upon a time, there was a foo and a bar."
story = story.replace("bar", word2);
story = story.replace("foo", word1);
story
的值将为"Once upon a time, there was a bar and a bar."
我的目标是把story
变成"Once upon a time, there was a bar and a foo."
,我该怎么做呢?
发布于 2014-11-07 07:58:42
使用Apache Commons StringUtils中的replaceEach()
方法
StringUtils.replaceEach(story, new String[]{"foo", "bar"}, new String[]{"bar", "foo"})
发布于 2014-11-10 10:45:16
这里有一个使用Map的不太复杂的答案。
private static String replaceEach(String str,Map<String, String> map) {
Object[] keys = map.keySet().toArray();
for(int x = 0 ; x < keys.length ; x ++ ) {
str = str.replace((String) keys[x],"%"+x);
}
for(int x = 0 ; x < keys.length ; x ++) {
str = str.replace("%"+x,map.get(keys[x]));
}
return str;
}
方法被调用
Map<String, String> replaceStr = new HashMap<>();
replaceStr.put("Raffy","awesome");
replaceStr.put("awesome","Raffy");
String replaced = replaceEach("Raffy is awesome, awesome awesome is Raffy Raffy", replaceStr);
输出结果是: Raffy很棒,Raffy Raffy很棒
发布于 2014-11-07 08:39:23
如果您希望能够处理要替换的多个搜索字符串,可以很容易地通过在每个搜索项上拆分字符串,然后替换它来实现。下面是一个示例:
String regex = word1 + "|" + word2;
String[] values = Pattern.compile(regex).split(story);
String result;
foreach subStr in values
{
subStr = subStr.replace(word1, word2);
subStr = subStr.replace(word2, word1);
result += subStr;
}
https://stackoverflow.com/questions/26791441
复制相似问题