如何以一种最终不会替换另一个字符串的方式替换两个字符串? [英] How can I replace two strings in a way that one does not end up replacing the other?

查看: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 的值将是 从前,有一个 foo 和一个 foo."

After this code runs, the value of story will be "Once upon a time, there was a foo and a 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 的值将是 从前,有一个酒吧和一个酒吧."

我的目标是将 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?

推荐答案

使用 replaceEach() 方法来自 Apache Commons StringUtils:

StringUtils.replaceEach(story, new String[]{"foo", "bar"}, new String[]{"bar", "foo"})

这篇关于如何以一种最终不会替换另一个字符串的方式替换两个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆