如何替换两个字符串,以使一个字符串最终不会替换另一个字符串?

发布于 2021-01-30 16:40:11

假设我有以下代码:

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."我怎么能做到呢?

关注者
0
被浏览
143
1 个回答
知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看