Say I had the string “foo1bar2” and I wanted to replace to perform the following replacements in parallel with an expected output of “bar1foo2”.
foo => bar
bar => foo
The string cannot be tokenized as the substrings might occur anywhere, any number of times.
A naive approach would to be to replace like this, however it would fail as the 2nd replacement would undo the first.
String output = input.replace("foo", "bar").replace("bar", "foo");
=> foo1foo2
or
String output = input.replace("bar", "foo").replace("foo", "bar");
=> bar1bar2
I’m not sure regex can help me here either? This isn’t homework by the way, just geeky interest. I’ve tried googling this but unsure how to describe the problem.
Try first replacing “foo” with something else that won’t occur anywhere else in the String. Then replace “bar” with “foo” then replace the temporary replacement from step 1 with “bar”.