如何以一种不会最终替换另一种的方式替换两个字符串? [英] How can I replace two strings in a way that one does not end up replacing the other?
本文介绍了如何以一种不会最终替换另一种的方式替换两个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下代码:
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的值
将曾几何时,有一个foo和foo。
出现类似的问题如果我以相反的顺序替换它们:
A similar issue occurs if I replaced them in the opposite order:
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
的值将曾几何时,有一个酒吧和一个酒吧。
我的目标是转故事
进入曾几何时,有一个酒吧和一个foo。
我怎么能做到这一点?
My goal is to turn story
into "Once upon a time, there was a bar and a foo."
How could I accomplish that?
推荐答案
使用 来自 方法/StringUtils.htmlrel =noreferrer> Apache Commons StringUtils
:
StringUtils.replaceEach(story, new String[]{"foo", "bar"}, new String[]{"bar", "foo"})
这篇关于如何以一种不会最终替换另一种的方式替换两个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文