Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (1.1k 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 (13.2k points)

You can either use a temporary value or use replaceEach().

  1. Using temporary value

 You can use a temporary intermediate value which is not yet  present in the string like,

story = story.replace("foo", "temp");

story = story.replace("bar", "foo");

story = story.replace("temp", "bar");

  1. Using replaceEach()

You can directly use replaceEach(), which will give you your desired result.

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

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
+1 vote
1 answer

Browse Categories

...