检查一个字符是元音还是辅音?

问题描述 投票:0回答:14

是否有代码可以检查一个字符是元音还是辅音?像 char = IsVowel 这样的东西?还是需要硬编码?

case ‘a’:
case ‘e’:
case ‘i’:
case ‘o’:
case ‘u’:
case ‘A’:
case ‘E’:
case ‘I’:
case ‘O’:
case ‘U’:
c# character
14个回答
42
投票

你可以这样做:

char c = ...
bool isVowel = "aeiouAEIOU".IndexOf(c) >= 0;

或者这个:

char c = ...
bool isVowel = "aeiou".IndexOf(c.ToString(), StringComparison.InvariantCultureIgnoreCase) >= 0;

一旦添加了对

éèe̋ȅëêĕe̊æøи
等内容的国际支持,这个字符串就会变长,但基本解决方案是相同的。


10
投票

这是一个有效的函数:

public static class CharacterExtentions
{
    public static bool IsVowel(this char c)
    {
        long x = (long)(char.ToUpper(c)) - 64;
        if (x*x*x*x*x - 51*x*x*x*x + 914*x*x*x - 6894*x*x + 20205*x - 14175 == 0) return true;
        else return false;
    }
}

像这样使用它:

char c = 'a';
if (c.IsVowel()) { // it's a Vowel!!! }

(是的,它确实有效,但显然,这是一个笑话答案。不要对我投反对票。或其他什么。)


4
投票

不。您需要首先定义什么是元音和辅音。例如,在英语中,“y”可以是辅音(如“yes”)或元音(如“by”)。像“é”和“ü”这样的字母可能在所有使用它们的语言中都是元音,但似乎您根本没有考虑它们。首先,您应该定义为什么希望将字母分类为辅音和元音。


4
投票
Console.WriteLine("Please input a word or phrase:");
string userInput = Console.ReadLine().ToLower();

for (int i = 0; i < userInput.Length; i++)
        {
            //c stores the index of userinput and converts it to string so it is readable and the program wont bomb out.[i]means position of the character.
            string c = userInput[i].ToString();
            if ("aeiou".Contains(c))
            {
                vowelcount++;
            }
        }
        Console.WriteLine(vowelcount);

2
投票

其他方法也有效。这里我关心的是性能。对于我测试的两种方法 - 使用 LINQ 的 Any 方法和使用位算术,使用位算术的速度要快十倍以上。结果:

LINQ 时间 = 117 毫秒

位掩码时间 = 8 毫秒

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);
}

有关计时测试中的代码,请参阅 https://dotnetfiddle.net/WbPHU4

位掩码的关键思想是第二位设置为“a”,第六位设置为“e”等。然后,将字母左移其 ASCII 值作为整数,然后看到如果掩码中的该位被设置。每个元音的掩码中设置一位,OR 运算首先执行字母的小写。


1
投票

您可以根据需要使用“IsVowel”。然而,唯一的问题是,可能没有默认的 C# 库或函数可以开箱即用地执行此操作,如果这是您想要的。您需要为此编写一个 util 方法。

bool a = isVowel('A');//example method call 

public bool isVowel(char charValue){
    char[] vowelList = {'a', 'e', 'i', 'o', 'u'};

    char casedChar = char.ToLower(charValue);//handle simple and capital vowels

    foreach(char vowel in vowelList){
        if(vowel == casedChar){
            return true;
        }
    }

    return false;
}    

1
投票

这个效果很好。

public static void Main(string[] args)
    {
        int vowelsInString = 0;
        int consonants = 0;
        int lengthOfString;
        char[] vowels = new char[5] { 'a', 'e', 'i', 'o', 'u' };

        string ourString;
        Console.WriteLine("Enter a sentence or a word");
        ourString = Console.ReadLine();
        ourString = ourString.ToLower();

        foreach (char character in ourString)
        {
            for (int i = 0; i < vowels.Length; i++)
            {
                if (vowels[i] == character) 
                {
                    vowelsInString++;
                }
            }
        }
        lengthOfString = ourString.Count(c => !char.IsWhiteSpace(c)); //gets the length of the string without any whitespaces
        consonants = lengthOfString - vowelsInString; //Well, you get the idea.
        Console.WriteLine();
        Console.WriteLine("Vowels in our string: " + vowelsInString);
        Console.WriteLine("Consonants in our string " + consonants);
        Console.ReadKey();
    }
}

0
投票

为什么不创建一个元音/辅音数组并检查该值是否在数组中?


0
投票

你可以这样做。

  private bool IsCharacterAVowel(char c)
  {
     string vowels = "aeiou";
     return vowels.IndexOf(c.ToString(),StringComparison.InvariantCultureIgnoreCase) >= 0;      
  }

0
投票

您可以使用以下扩展方法:

using System;
using System.Linq;

public static class CharExtentions
{
    public static bool IsVowel(this char character)
    {
        return new[] {'a', 'e', 'i', 'o', 'u'}.Contains(char.ToLower(character));
    }
}

像这样使用它:

'c'.IsVowel(); // Returns false
'a'.IsVowel(); // Returns true

0
投票
return "aeiou".Any( c => c.Equals( Char.ToLowerInvariant( myChar ) ) );

0
投票

试试这个:

char[] inputChars = Console.ReadLine().ToCharArray();
int vowels = 0;
int consonants = 0;
foreach (char c in inputChars)
{
   if ("aeiou".Contains(c) || "AEIOU".Contains(c))
   {
       vowels++;
   }
   else
   {
       consonants++;
   }
}
Console.WriteLine("Vowel count: {0} - Consonant count: {1}", vowels, consonants);
Console.ReadKey();

0
投票

查看此代码以检查元音和辅音,C#

private static void Vowel(string value)
{
    int vowel = 0;
    foreach (var x in value.ToLower())
    {
        if (x.Equals('a') || x.Equals('e') || x.Equals('i') || x.Equals('o') || x.Equals('u'))
        {
            vowel += 1;
        }
    } 
    Console.WriteLine( vowel + " number of vowels");
}

private static void Consonant(string value)
{
    int cont = 0;
    foreach (var x in value.ToLower())
    {
        if (x > 'a' && x <= 'd' || x > 'e' && x < 'i' || x > 'j' && x < 'o' || x >= 'p' && x < 'u' || x > 'v' && x < 'z')
        {
            cont += 1;
        }
    }
    Console.WriteLine(cont + " number of consonant");
}

0
投票

不幸的是,现有的答案都不能处理重音字母。以下代码确实如此(事实上,仅适用于拉丁字母,但修改或包含其他字母也非常简单):

public static string IsFirstVowel(this string s) {
  char[] Vowels = new[] { 'a', 'e', 'i', 'o', 'u' };
  string Normalized = s.First().ToString().ToLowerInvariant().Normalize(NormalizationForm.FormD);
  foreach (char c in Normalized) {
    if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark) {
      Normalized = c.ToString().Normalize(NormalizationForm.FormC);
      return Vowels.Contains(Normalized.First());
    }
  }
  return false;
}
© www.soinside.com 2019 - 2024. All rights reserved.