如何替换两个字符串,以使一个字符串最终不会替换另一个字符串?
假设我有以下代码:
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"})
-
在两个字符串之间替换一个字符串
2021-01-30 关注 0 浏览112 1答案
-
pandas:用另一个字符串替换字符串
2021-01-29 关注 0 浏览96 1答案
-
如何检查另一个字符串中是否存在一个字符串
2021-02-02 关注 0 浏览94 1答案
-
如何检查一个字符串“StartsWith”是否是另一个字符串?
2022-02-17 关注 0 浏览61 1答案
-
如何将一个字符串中的一个字符与另一个字符串进行比较
2021-01-30 关注 0 浏览221 1答案
-
如何在Python中将一个字符串附加到另一个字符串?
2021-02-02 关注 0 浏览121 1答案
-
如何在 Python 中将一个字符串附加到另一个字符串?
2022-03-22 关注 0 浏览81 1答案
-
检查一个字符串是否包含另一个字符串
2022-05-26 关注 0 浏览30 1答案
-
如何检查一个变量是否等于一个字符串或另一个字符串?
2021-01-29 关注 0 浏览141 1答案
-
用C#中的另一个字符串分割一个字符串
2021-02-02 关注 0 浏览201 1答案