String inputString = args[0];
String out2 = inputString.replaceAll("I", "you");
String out1 = out2.replaceAll("you", "I");
System.out.println(out1);
Above is the code in the main method. It's supposed to replace "I" for "you", and "you" for "I", but instead only the latter call to replaceAll() works (as in, the one called on out2). When running, I've set the first argument which is taken as the input string to "I hate everything about you" which should switch I for you and vice versa, but instead "I hate everything about I" is outputted.
Any ideas?
Cheers
That's because all the I's
have already become you
, by the time you replace the you's
.
You need to use an intermediate replacement value for these kinds of replacement to work like this:
inputString = inputString.replaceAll("I", "_I_")
.replaceAll("you", "I")
.replaceAll("_I_", "you");
This assuming that, your intermediate value("_I_"
) is not already in your string. So, that you have to choose carefully.