Reputation: 183
I want to do something like this:
String myString="123EDCBAabcde";
myString=myString.passValidChars("ABCDE");
now myString is "EDCBA"
Is there already a function which only passes the valid characters and removes the others? If not what is the best way to do this?
Best Regards.
Upvotes: 0
Views: 1083
Reputation: 604
String string = "123EDCBAabcde";
Pattern pattern = Pattern.compile("[ABCDE]");
Matcher mach = pattern.matcher(string);
StringBuffer str = new StringBuffer();
while(mach.find()){
str.append(mach.group());
}
string = str.toString(); // Now string is "EDCBA"
Upvotes: 1
Reputation: 15685
Related to @JB Nizet answer:
static String passValidChar(String in, String validChar){
StringBuilder strBuilder = new StringBuilder();
for(char c : in.toCharArray()){
if(validChar.indexOf(String.valueOf(c)) != -1){
strBuilder.append(c);
}
}
return strBuilder.toString();
}
public static void main(String [] args){
System.out.println(passValidChar("123EDCBAabcde", "EDCBA"));
}
Upvotes: 0
Reputation: 2812
Guava library (google collections) has the exact class you need: CharMatcher
http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf
Pages 12 up to 19.
Upvotes: 0
Reputation: 691963
This is trival to implement.
myString
. Upvotes: 3