假设我有以下代码:
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."
我怎样才能做到呢?