is it possible to check if a char matches a list of possibilities?

前端 未结 4 1035
温柔的废话
温柔的废话 2020-12-03 19:13

For example I know that when checking strings, you can do something like

if (string.matches(\"a|e|i|o|u|A|E|I|O|U\" ) )
{
   // Then do this code.
}
<         


        
相关标签:
4条回答
  • 2020-12-03 19:20

    You could make a collection of chars that you want to check, and see if the collection contains the char in question. A HashSet is ideal here for O(1) look up time. (not that it matters, because the size is constant.)

    private static final HashSet<Character> vowels = new HashSet<Character>();
    
    //Initialize vowels hashSet to contain vowel characters
    static{
        vowels.add('a');
        vowels.add('e');
        vowels.add('i');
        vowels.add('o');
        vowels.add('u');
        vowels.add('A');
        vowels.add('E');
        vowels.add('I');
        vowels.add('O');
        vowels.add('U');
    }
    
    public static boolean isVowel(Character c){
        return vowels.contains(c);
    }
    
    0 讨论(0)
  • 2020-12-03 19:21

    From the performance standpoint the optimum approach would be this:

    private final BitSet matchChars = matchChars();
    
    private BitSet matchChars() {
      final BitSet bs = new BitSet();
      final String matchString = "aeiouAEIOU";
      for (int i = 0; i < matchString.length(); i++)
         bs.set(matchString.charAt(i));
      return bs;
    }
    
    public boolean charMatches(char c) { return matchChars.get(c); }
    

    Memory required for the approach is very modest even if you use the whole 16-bit range afforded by the char type: at most 8 KB.

    0 讨论(0)
  • 2020-12-03 19:29

    You can do something similar when looking for a char in a String, by using the indexOf method to search the string.

    if ("aeiouAEIOU".indexOf(aChar) != -1)
    
    0 讨论(0)
  • 2020-12-03 19:42

    Back before we had Unicode, when the character set was only 128 characters (ASCII) or later 256 (ISO 8859-1), we would often just create an array of Booleans and use a lookup on the character code--very fast. You could still do the same (an array of 65536 booleans isn't all that big by today's memory standards), or something like

    static boolean[] vowelSet = new boolean[128]; // all initialized to false by default
    
    static {
        vowelSet['A'] = true;
        vowelSet['E'] = true;
        ...
        vowelSet['u'] = true;
    }
    

    and then to look up:

    boolean isVowel(char ch) {
        return ch < 128 && vowelSet[ch];
    }
    

    I think that's still the approach I'd take if efficiency were extremely important. Usually it isn't, so one of the other answers probably gives you more readable code.

    0 讨论(0)
提交回复
热议问题