Reputation: 87
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);
}
}
1c1g1
11c111g111111111111111111
Upvotes: 0
Views: 102
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);
}
}
Upvotes: 2