suchit
suchit

Reputation: 87

How to replace all characters in a String except certain character?

public class HelloWorld {
    public static void main(String []args) {
        //replace all char to 1 other then c and g
        String str = "abcdefghijklmnopqrstuvwxyz";
        if (str == null || str.length() == 0) {
            return;
        }
        String answer = str.replaceAll("[^cg]+", "1");
        System.out.println(answer);
    }
}

Upvotes: 0

Views: 102

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074475

Now here I am getting an output as 1c1g1, but what I want is 11c111g111111111111111111

Remove the +. That says "match one or more of the previous" but you're replacing that series of matching characters with one 1.

So:

public class HelloWorld {

    public static void main(String []args){
        //replace all char to 1 other then c and g
        String str = "abcdefghijklmnopqrstuvwxyz";
        if (str == null || str.length() == 0) {
            return;
        }
        String answer = str.replaceAll("[^cg]", "1");
        // No + here ------------------------^
        System.out.println(answer);
    }
}

Live Copy

Upvotes: 2

Related Questions