18

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

case ‘a’:
case ‘e’:
case ‘i’:
case ‘o’:
case ‘u’:
case ‘A’:
case ‘E’:
case ‘I’:
case ‘O’:
case ‘U’:
4

13 回答 13

38

你可以这样做:

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

或这个:

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

一旦你为诸如此类的东西添加了国际支持,éèe̋ȅëêĕe̊æøи这个字符串就会变长,但基本的解决方案是一样的。

于 2013-07-20T17:25:11.107 回答
8

这是一个有效的功能:

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!!! }

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

于 2013-07-20T17:36:23.117 回答
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);
于 2013-07-21T00:08:13.953 回答
4

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

于 2013-07-20T18:54:03.530 回答
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();
    }
}
于 2014-10-17T08:19:51.713 回答
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;
}    
于 2013-07-20T17:41:57.027 回答
1

给出的其他方法有效。这里我关心的是性能。对于我测试的两种方法——使用 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 操作首先执行字母的小写。

于 2018-04-19T17:25:24.180 回答
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();
于 2014-06-20T17:20:15.337 回答
0
return "aeiou".Any( c => c.Equals( Char.ToLowerInvariant( myChar ) ) );
于 2014-04-28T03:45:40.817 回答
0

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

于 2013-07-20T17:41:38.327 回答
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
于 2013-07-20T19:04:17.637 回答
0

你可以在里面做这样的事情。

  private bool IsCharacterAVowel(char c)
  {
     string vowels = "aeiou";
     return vowels.IndexOf(c.ToString(),StringComparison.InvariantCultureIgnoreCase) >= 0;      
  }
于 2013-07-20T17:23:33.230 回答
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");
}
于 2018-02-13T14:13:23.660 回答