Check if a character is a vowel or consonant?

前端 未结 13 1281
别那么骄傲
别那么骄傲 2020-12-09 09:57

Is there a code to check if a character is a vowel or consonant? Some thing like char = IsVowel? Or need to hard code?

case ‘a’:
case ‘e’:
case ‘i’:
case ‘o’         


        
13条回答
  •  没有蜡笔的小新
    2020-12-09 10:47

    The other methods given work. Here I am concerned with performance. For the two approaches I tested - using LINQ's Any method and using bit arithmetic, the use of bit arithmetic was more than ten times faster. Results:

    Time for LINQ = 117 msec

    Time for Bit masks = 8 msec

    public static bool IsVowelLinq(char c)
    {
        char[] vowels = new[] { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' };
        return vowels.Any(ch => ch == c);
    }
    
    private static int VowelMask = (1 << 1) | (1 << 5) | (1 << 9) | (1 << 15) | (1 << 21);
    
    public static bool IsVowelBitArithmetic(char c)
    {
        // The OR with 0x20 lowercases the letters
        // The test c > 64 rules out punctuation, digits, and control characters.
        // An additional test would be required to eliminate characters above ASCII 127.
        return (c > 64) && ((VowelMask &  (1 << ((c | 0x20) % 32))) != 0);
    }
    

    See https://dotnetfiddle.net/WbPHU4 for the code in a test with timings.

    The key idea with the bit mask is that the second bit is set for 'a', the sixth bit is set for 'e', etc. Then you take the letter, shift left by its ASCII value as an integer, and see if that bit in the mask is set. One bit is set in the mask for each vowel, and the OR operation performs the lowercasing of the letter first.

提交回复
热议问题