Suppose I have the string "John is distinguished" and I wish to replace "is" with "FOO". When I use the replace methods, Java returns this string "John FOO dFOOtinguFOOhed" rather than the expected result, "John FOO distinguished". Java replaced every literal occurrence of "is" in the string with "FOO" which is not the intended result.
I would prefer not to invoke the replace method this way, replace(" is ", "FOO"), because any occurrence of "is" that is next to a punctuation or comma will be ignored. Example, calling replace this way with the input string "John is… distinguished" would result in the same string "John is… distinguished" rather than the correct output "John FOO… distinguished".
>Solution :
Can you try using regular expressions like the ff?
String string = "John is distinguished";
String result = string.replaceAll("\\bis\\b","FOO");
System.out.Println(result);
The "\\b" ensure that "is" is matched as whole word rather than just a part of the complete word, in a way ensure word boundary.