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

前端 未结 4 1034
温柔的废话
温柔的废话 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 vowels = new HashSet();
    
    //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);
    }
    

提交回复
热议问题