【问题标题】:Check if a character is a vowel or consonant?检查一个字符是元音还是辅音?
【发布时间】:2013-07-20 17:19:38
【问题描述】:

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

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

【问题讨论】:

标签: c# character


【解决方案1】:

你可以这样做:

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

或者这个:

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

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

【讨论】:

  • 或者对于 .NET 3.5 或更高版本,只需 "aeiouAEIOU".Contains(c)。
  • @JukkaK.Korpela 因为并非总是如此。在“Why”中,它被认为是一个元音,而在“Yawn”中,它是一个辅音。
  • InvariantCulture 不照顾 éèe̋ȅëêĕe̊æøи 吗?所以 é = e 并且您不必将它们附加到您的字符串中。
  • @gijswijs 编号:"é".Equals("e", StringComparison.InvariantCultureIgnoreCase) → False.
【解决方案2】:

这是一个有效的函数:

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

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

【讨论】:

  • 匿名投票者 - 你显然没有听从我的指示。或者也许你做到了——我不确定。 ;)
  • 不是我的反对意见,但我猜原因是您没有解释 如何 这是如何工作的。对于dot-less lowercase i (ı),它也恰好返回 true,但对于其他非拉丁元音则没有。
  • 有趣的是,“无点小写 i”返回 'true' - 它一定是 char.ToUpper 的怪癖。至于不解释它是如何工作的,就像大多数笑话一样(因为我确实清楚地认为这是一个笑话),如果我必须解释它,那么它就会失去所有的乐趣。我想会有两组人——那些立即理解它是如何工作的,并且会欣赏“独创性”(不管有多少),以及那些一开始没有得到它,但可能会很有趣的人时间弄清楚。当然,如果有人想不通并问,那么我很乐意解释。
  • 这是最好的解决方案!
  • 好的,太棒了!你能解释一下它是如何工作的吗?此外,您可以只返回“if”条件并减少额外的代码行。 :)
【解决方案3】:

没有。您需要首先定义您认为的元音和辅音。例如,在英语中,“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);
    

    【讨论】:

      【解决方案5】:

      您可以根据需要使用“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;
      }    
      

      【讨论】:

      • 这显然不是 C#,这就是 OP 将他的问题标记为的内容。
      • 啊,你错了,它最初是用 Java 编写的,现在是 C#
      【解决方案6】:

      这很好用。

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

      【讨论】:

        【解决方案7】:

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

        【讨论】:

        • 在 LINQ 版本中调用“new”是它运行缓慢的主要原因。
        • 另外,数组搜索速度太慢。将“元音”设为 HashSet 并将其移动到静态成员中,它的速度比位掩码快 10 倍,而且只慢一点。
        【解决方案8】:

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

        【讨论】:

          【解决方案9】:

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

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

          【讨论】:

          • 这是区分大小写的
          • @SriramSakthivel 他想要一个不工作代码的想法。编写伪代码只是为了让他知道他应该做什么。
          【解决方案10】:

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

          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
          

          【讨论】:

            【解决方案11】:
            return "aeiou".Any( c => c.Equals( Char.ToLowerInvariant( myChar ) ) );
            

            【讨论】:

            • 更清晰的代码将是如果您将值转换为较低的值并使用“包含”
            【解决方案12】:

            试试这个:

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

            【讨论】:

              【解决方案13】:

              查看此代码以检查元音和辅音,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");
              }
              

              【讨论】:

                猜你喜欢
                • 2020-06-20
                • 1970-01-01
                • 2023-02-03
                • 2022-11-17
                • 1970-01-01
                • 2016-06-11
                • 1970-01-01
                • 1970-01-01
                • 2016-04-02
                相关资源
                最近更新 更多