Jin
Jin

Reputation: 165

Substring replacement in Java

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

}

Upvotes: 2

Views: 383

Answers (3)

Yogendra Singh
Yogendra Singh

Reputation: 34367

Obviously you were missing the Left hand assignment to make your code working with given conditions.

    input.replace("PI", "3.14");

But it will only replace, if input contains PI while it will attempt for pi and Pi as well. To better handle this, I think you can use "[pP][iI]" or "[pP]{1}[iI]{1}" as replacement pattern, which will look for one occurrence of P or p followed by one occurrence of I or i e.g. below:

   String input = "xPIyPizpIapib";
   input = input.replaceAll("[pP][iI]", "3.14"); 
   System.out.println(input); //<- all "pi"s irrespective of case are replaced.

   String input = "xPIyPizpIapib";
   input = input.replaceAll("[pP]{1}[iI]{1}", "3.14"); 
   System.out.println(input); //<- all "pi"s irrespective of case are replaced.

Please Note: This will also replace pI as wel, if found.

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234795

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

Upvotes: 2

arshajii
arshajii

Reputation: 129507

Strings are immutable!!

input = input.replace("PI", "3.14");

Upvotes: 8

Related Questions