如何替换两个字符串,以使一个字符串最终不会替换另一个字符串?
假设我有以下代码:
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."
我怎么能做到呢?
-
使用Apache Commons StringUtils中的
replaceEach()
方法:StringUtils.replaceEach(story, new String[]{"foo", "bar"}, new String[]{"bar", "foo"})