Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 2nd, 2012  |  syntax: None  |  size: 0.64 KB  |  hits: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Best way/algorithm to find out if a string consists of only a given set of characters
  2. Input 8888338385
  3.      Output VALID
  4. Input 887837348234
  5. Output : Invalid
  6.        
  7. public boolean isValidString(String str) {
  8.   return str.matches("[358]*");
  9. }
  10.        
  11. import java.util.regex.Pattern;
  12.  
  13. public class Matcher {
  14.   private Pattern pattern;
  15.  
  16.   public Matcher() {
  17.     this.pattern = Pattern.compile("[358]*");
  18.   }
  19.  
  20.   public isValid(String str) {
  21.     return pattern.matcher(str).matches();
  22.   }
  23. }
  24.        
  25. const char* haystack = "8888338385";
  26. const char* filter = "385";
  27.  
  28. if (strlen(haystack) != strspn(haystack, filter))
  29. {
  30.   // oops - haystack contains more characters...
  31. }