Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (4k points)

Let's say that I have the following code:

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);

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);

The value of story will be "Once upon a time, there was a bar and a bar."

My goal is to turn story into "Once upon a time, there was a bar and a foo." How could I accomplish that?

1 Answer

0 votes
by (46k points)

Use the replaceEach() method from Apache Commons StringUtils:

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

Related questions

0 votes
1 answer
0 votes
1 answer
asked Jul 10, 2019 in Java by Nigam (4k points)
0 votes
1 answer

Browse Categories

...