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

前端 未结 4 1039
温柔的废话
温柔的废话 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: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.

提交回复
热议问题