I am trying to implement substring replacement, but I am not getting the desired results. Can someone comment on what I may missing here?
public class SubtringReplacement {
public static void main (String[] args){
String input = "xPIy";
if (input.contains("PI") || input.contains("pi") || input.contains("Pi")){
input.replace("PI", "3.14");
}
System.out.println(input);
}
}
Strings are immutable!!
input = input.replace("PI", "3.14");
One problem is that you need to capture the return value when you do the replacement. The other problem is that you will only replace upper case "PI", while it seems you want to replace mixed case instances. Try this instead:
input = input.replaceAll("(PI|pi|Pi)", "3.14");
replace looks for a literal match; replaceAll does a regular expression match, which is what you need.
By the way, you don't need the if condition -- if there is no match, there will be no replacement.
P.S. Look at the comment by @NullUserException if you also want to replace instances of "pI".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With