【发布时间】:2015-01-03 15:59:17
【问题描述】:
假设我有以下代码:
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." 我怎样才能做到这一点?
【问题讨论】:
-
+1 肯定应该有一些函数
swap(String s1, String s2, String s3)将所有出现的s2与s3交换,反之亦然。 -
我们可以假设输入中每个可交换的词只出现一次吗?
-
极端情况:在“ababababababa”中交换“ab”和“ba”时,我们期望输出什么?
-
您在下面有一些很好的解决方案,但是您了解为什么您的方法不起作用吗?首先,你有“有一个 foo 和一个酒吧”。在第一次替换 ("foo"->"bar") 之后,你有“有一个 bar 和一个 bar”。您现在出现了 2 次“bar”,因此您的第二次替换没有达到您的预期 - 它无法知道您只想替换上次没有替换的那个。 @HagenvonEitzen 有趣。我希望一个可行的解决方案能够匹配并替换它找到的任一字符串中的第一个,然后从替换部分的末尾重复。
-
Jeroen 的解决方案是我在文本编辑器中经常使用的解决方案,当我需要进行批量重命名时。它简单易懂,不需要特殊的库,稍加思考就可以万无一失。