Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substring replacement in Java

Tags:

java

substring

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);
    }

}
like image 889
Jin Avatar asked Apr 10 '26 13:04

Jin


2 Answers

Strings are immutable!!

input = input.replace("PI", "3.14");
like image 190
arshajii Avatar answered Apr 12 '26 02:04

arshajii


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".

like image 25
Ted Hopp Avatar answered Apr 12 '26 01:04

Ted Hopp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!