如何以一个字符串最终不会替换另一个字符串的方式替换两个字符串?
假设我有以下代码:
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."