【问题标题】:C# Count VowelsC# 计数元音
【发布时间】:2013-08-09 05:07:27
【问题描述】:

我正在学习 C# 编程,我正在尝试计算元音。我让程序循环遍历句子,但不是返回元音计数,而是返回字符串的长度。任何帮助将不胜感激。

    static void Main()
    {
        int total = 0;

        Console.WriteLine("Enter a Sentence");
        string sentence = Console.ReadLine().ToLower();

        for (int i = 0; i < sentence.Length; i++)
        {
            if (sentence.Contains("a") || sentence.Contains("e") || sentence.Contains("i") || sentence.Contains("o") || sentence.Contains("u"))
            {
                total++;
            }
        }
        Console.WriteLine("Your total number of vowels is: {0}", total);

        Console.ReadLine();
    }

【问题讨论】:

  • 你每次都在使用 sentence.contains(),如果句子有元音,这将永远是真的!你需要一个字母一个字母地测试。
  • 您的 for 循环遍历每个字符,但您实际上并没有使用该字符,而是每次检查整个句子是否包含元音。
  • 这是因为您每次都检查整个句子而不是字符。因此,只要它包含至少 1 个元音,您将始终得到长度

标签: c# loops console-application


【解决方案1】:
`public static void Main()
{
    Console.WriteLine("Enter a Sentence");
    string sentence = Console.ReadLine().ToLower();

    string voval="aeiou";
    int cnt=0;
    foreach(char ch in sentence)
    {
        if(voval.Contains(ch.ToString()))
        {
            cnt++;
        }
    }
    Console.WriteLine(cnt); 
}`

【讨论】:

    【解决方案2】:

    我们检查表达式的每个后续字母是否等于数组中的元音

    class Program
    {
    
        private static void Main(string[] args)
        {
            string random = Console.ReadLine();
            string toLower = random.ToLower();
            char []isVowels = { 'a','e','i','o','u','y' };
            byte count = 0;
            for (int i = 0; i < toLower.Length; i++)
            {
                for (int j = 0; j < isVowels.Length; j++)
                {
                    if (toLower[i]==isVowels[j])
                    {
                        count++;
                    }
                }
            }
            Console.WriteLine(count);
        }
        
    
    }
    

    【讨论】:

      【解决方案3】:

      // 使用两个循环。

              char[] vowels= new char[]{'a', 'e', 'i', 'o', 'u',
                                         'A', 'E', 'I', 'O', 'U'}; 
              string myWord= "This is a beautiful word.";
              
              int numVowels = 0;
              
              foreach(char c in  myWord.ToCharArray())
              {
                  foreach(char c2 in vowels)
                  {
                      if(c == c2) numVowels++;    
                  }  
              }
              
              Console.WriteLine($"{numVowels} vowels in: {myWord}");
      

      【讨论】:

        【解决方案4】:

        我们可以使用正则表达式来匹配句子中的元音。

        Regex.Matches() 函数将返回一个包含所有出现元音的数组。 然后我们可以使用 count 属性来计算元音的个数。

        匹配字符串中元音的正则表达式:[aeiouAEIOU]+

        下面是工作代码sn-p:

         public static void Main()
           {
               string pattern = @"[aeiouAEIOU]+";
               Regex rgx = new Regex(pattern);
               string sentence = "Who writes these notes?";
               Console.WriteLine(rgx.Matches(sentence).Count);
           }
        

        【讨论】:

          【解决方案5】:

          应用计算句子中的元音和辅音字母。 这是另一种代码行更少的解决方案,了解使用循环和嵌套循环与 char 数组的想法。

          具有控件名称的应用程序接口:

          namespace Program8_4
          {
            public partial class Form1 : Form
            {
              // declare the counter variables in field
              int iNumberOfVowels = 0;
              int iNumberOfConsonants = 0;
              public Form1()
              {
                  InitializeComponent();
              }
          
              private void btnFind_Click(object sender, EventArgs e)
              {
                  // call the methods in this event
                  GetVowels(txtStringInput.Text);
                  GetConsonants(txtStringInput.Text);
                  // show the result in a label
                  lblOutput.Text = "The number of vowels : " + iNumberOfVowels.ToString()+ Environment.NewLine+
                      "The number of consonants : " + iNumberOfConsonants.ToString();
                  // assign zero the counters to not add the previous number to new number, and start counting from zero again
                  iNumberOfVowels = 0;
                  iNumberOfConsonants = 0;
          
              }
          
              private int GetConsonants(string strFindConsonants)
              {
                  // Declare char array to contain consonants letters
                  char[] chrConsonants = { 'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'X',
                      'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'x' };
          
                  // loop to get each letter from sentence
                  foreach (char Consonants in strFindConsonants)
                  {
                  // another nested loop to compare each letter with all letters contains in chrConsonants array
                      for (int index= 0; index<chrConsonants.Length;index++)
                      {
                          // compare each letter with each element in charConsonants array
                          if (Consonants == chrConsonants[index])
          
                          {
                              // If it is true add one to the counter iNumberOfConsonants
                              iNumberOfConsonants++;
                        }
          
                      }
                  }
                  // return the value of iNumberOfConsonants
                  return iNumberOfConsonants;
              }
          
              private int GetVowels(string strFindVowels)
          
              {
                  // Declare char array to contain vowels letters
                  char[] chrVowels = { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O','U' };
          
                  // loop to get each letter from sentence
                  foreach (char Vowels in strFindVowels)
                  {
                      // another nested loop to compare each letter with all letters contains in chrVowels array
                      for (int index = 0; index< chrVowels.Length; index++)
                      {
                          // compare each letter with each element in chrVowels array
                          if (Vowels == chrVowels[index])
          
                      {
                              // If it is true add one to the counter iNumberOfVowels
                              iNumberOfVowels = iNumberOfVowels+1;
          
                      }
                      }
                  }
                  // return the value of iNumberOfVowels
                  return iNumberOfVowels;
              }
          

          【讨论】:

            【解决方案6】:
                static void Main(string[] args)
                {
                    Char[] ch;
                    Console.WriteLine("Create a sentence");
                    String letters = Console.ReadLine().Replace(" ", "").ToUpper();
                    ch = letters.ToCharArray();
                    int vowelCounter = 0;
                    int consonantCounter = 0;
            
                   for(int x = 0; x < letters.Length; x++)
                    {
                        if(ch[x].ToString().Equals("A") || ch[x].ToString().Equals("E") || ch[x].ToString().Equals("I") || ch[x].ToString().Equals("O") || ch[x].ToString().Equals("U"))
                        {
                            vowelCounter++;
                        }
                        else
                        {
                            consonantCounter ++;
                        }
                    }
                    System.Console.WriteLine("Vowels counted : " + vowelCounter);
                    System.Console.WriteLine("Consonants counted : " + consonantCounter);
            

            【讨论】:

              【解决方案7】:
              void main()
              {
                  int x=0;
                  char ch;
                  printf("enter a statement:");
                  while((ch=getche())='\r')
                  {
                      if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')
                      x++;
                  }
                  printf("total vowels=");
                  getch();
              }
              

              【讨论】:

                【解决方案8】:

                这是一种很好的计算元音的通用方法,从这里你可以做各种各样的事情。计算元音,返回排序列表等。

                public static int VowelCount(String vowelName) {
                            int counter = 0;
                            char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
                            for (int index = 0; index < vowelName.Length; index++)
                            {
                                if (vowels.Contains(vowelName[index])) 
                                {
                                    counter++;
                                }
                            }
                            return counter;
                        }
                

                【讨论】:

                  【解决方案9】:
                  int cnt = 0;
                  for (char c in sentence.ToLower())
                      if ("aeiou".Contains(c))
                         cnt++;
                  return cnt;
                  

                  【讨论】:

                    【解决方案10】:

                    您正在检查您的整个句子是否包含循环的每次迭代的元音,这就是为什么您的总数只是句子字符串中的字符数。

                    foreach(char ch in sentence.ToLower())
                        if("aeiou".Contains(ch))
                            total++;
                    

                    最好还是使用正则表达式。 edit 您只想将正则表达式用于比匹配元音更复杂的事情。

                    using System.Text.RegularExpressions;
                    ...
                    int total = Regex.Matches(sentence, @"[AEIOUaeiou]").Count;
                    

                    编辑 仅出于完整性考虑,最快/最有效(如果您要在大约百万个字符串上执行此操作)解决方案。如果性能不是问题,我会使用 Linq 简洁。

                    public static HashSet<char> SVowels = new HashSet<char>{'a', 'e', 'i', 'o', 'u'};
                    public static int VowelsFor(string s) {
                        int total = 0;
                        foreach(char c in s)
                            if(SVowels.Contains(c))
                                total++;
                        return total;
                    }
                    

                    【讨论】:

                      【解决方案11】:

                      TMTOWTDI(正如他们所说的 Tim Toadie:有不止一种方法可以做到)。

                      怎么样

                      static char[] vowels = "AEIOUaeiou".ToCharArray() ;
                      public int VowelsInString( string s  )
                      {
                      
                        int n = 0 ;
                        for ( int i = 0 ; (i=s.IndexOfAny(vowels,i)) >= 0 ; )
                        {
                          ++n ;
                        }
                      
                        return n;
                      }
                      

                      或者(另一种正则表达式方法)

                      static readonly Regex rxVowels = new Regex( @"[^AEIOU]+" , RegexOptions.IgnoreCase ) ;
                      public int VowelCount( string s )
                      {
                        int n = rxVowels.Replace(s,"").Length ;
                        return n ;
                      }
                      

                      最直接的可能也是最快的:

                      public int VowelCount( string s )
                      {
                        int n = 0 ;
                        for ( int i = 0 ; i < s.Length ; +i )
                        {
                          switch( s[i] )
                          {
                          case 'A' : case 'a' :
                          case 'E' : case 'e' :
                          case 'I' : case 'i' :
                          case 'O' : case 'o' :
                          case 'U' : case 'u' :
                            ++n ;
                            break ;
                          }
                        }
                        return n ;
                      }
                      

                      【讨论】:

                        【解决方案12】:

                        你也可以用 switch 语句来做到这一点

                                var total = 0;
                                var sentence = "Hello, I'm Chris";
                                foreach (char c in sentence.ToLower())
                                {
                                    switch (c)
                                    {
                                        case 'a':
                                        case 'e':
                                        case 'i':
                                        case 'o':
                                        case 'u':
                                            total++;
                                            break;
                                        default: continue;
                                    }
                        
                                }
                                Console.WriteLine(total.ToString());
                        

                        【讨论】:

                          【解决方案13】:

                          既然 Reed 已经回答了您的问题,我将为您提供另一种实现方式。您可以使用 LINQ 和 lambda 表达式消除循环:

                          string sentence = "The quick brown fox jumps over the lazy dog.";
                          int vowelCount = sentence.Count(c => "aeiou".Contains(Char.ToLower(c)));
                          

                          如果您不理解这段代码,我强烈建议您在 C# 中查找 LINQ 和 Lambda 表达式。在很多情况下,您可以通过以这种方式消除循环来使代码更简洁。

                          本质上,这段代码是说“计算句子中包含在字符串“aeiou”中的每个字符。”

                          【讨论】:

                          • 谢谢。已编辑评论以正确说明这一点。
                          【解决方案14】:

                          给猫剥皮的方法有很多 :-) 在编程中,一点横向思维可能会很有用...

                          total += sentence.Length - sentence.Replace("a", "").Length;
                          total += sentence.Length - sentence.Replace("e", "").Length;
                          total += sentence.Length - sentence.Replace("i", "").Length;
                          total += sentence.Length - sentence.Replace("o", "").Length;
                          total += sentence.Length - sentence.Replace("u", "").Length;
                          

                          例如,您可以尝试从句子中删除元音,然后查看没有元音的句子是否更小,以及减少了多少。

                          【讨论】:

                            【解决方案15】:

                            这就是我的处理方式。

                            var sentence = "Hello my good friend";
                                        var sb = sentence.ToLower().ToCharArray();
                                        var count = 0;
                                        foreach (var character in sb)
                                        {
                                            if (character.Equals('a') || character.Equals('e') || character.Equals('i') || character.Equals('o') ||
                                                character.Equals('u'))
                                            {
                                                count++;
                                            }
                                        }
                            

                            【讨论】:

                              【解决方案16】:

                              对于初学者来说可能太高级了,但这是您在 C# 中执行此操作的方式:

                              var vowels = new[] {'a','e','i','o','u'};
                              
                              Console.WriteLine("Enter a Sentence");
                              var sentence = Console.ReadLine().ToLower();
                              
                              var vowelcount = sentence.Count(x => vowels.Contains(x));
                              
                              Console.WriteLine("Your total number of vowels is: {0}", vowelcount);
                              Console.ReadLine();
                              

                              【讨论】:

                                【解决方案17】:

                                或者使用 linq。

                                static void Main()
                                    {
                                        int total = 0;
                                
                                        Console.WriteLine("Enter a Sentence");
                                        string sentence = Console.ReadLine().ToLower();
                                        char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
                                
                                        total = sentence.Count(x => vowels.Contains(x));
                                
                                        Console.WriteLine("Your total number of vowels is: {0}", total);
                                
                                        Console.ReadLine();
                                    }
                                

                                【讨论】:

                                • 这看起来是一种过于复杂的方法,请原谅我,因为我使用 linq 已经有一段时间了,但这不会只返回 1 吗?
                                • 不,它返回字符串中元音的个数。
                                • @ReedCopsey 哎呀,当他阅读它时并没有意识到他调用了它。将修复
                                【解决方案18】:

                                那是因为你的if语句总是为真,你需要比较句[i]处的字符,看它是否是元音,而不是看句子是否包含元音。

                                【讨论】:

                                  【解决方案19】:

                                  现在,您正在检查整个句子 contains 是否有任何元音,每个字符一次。您需要改为检查各个字符。

                                     for (int i = 0; i < sentence.Length; i++)
                                      {
                                          if (sentence[i]  == 'a' || sentence[i] == 'e' || sentence[i] == 'i' || sentence[i] == 'o' || sentence[i] == 'u')
                                          {
                                              total++;
                                          }
                                      }
                                  

                                  话虽如此,您可以简化一下:

                                  static void Main()
                                  {
                                      int total = 0;
                                      // Build a list of vowels up front:
                                      var vowels = new HashSet<char> { 'a', 'e', 'i', 'o', 'u' };
                                  
                                      Console.WriteLine("Enter a Sentence");
                                      string sentence = Console.ReadLine().ToLower();
                                  
                                      for (int i = 0; i < sentence.Length; i++)
                                      {
                                          if (vowels.Contains(sentence[i]))
                                          {
                                              total++;
                                          }
                                      }
                                      Console.WriteLine("Your total number of vowels is: {0}", total);
                                  
                                      Console.ReadLine();
                                  }
                                  

                                  如果您想使用 LINQ,可以进一步简化:

                                  static void Main()
                                  {
                                      // Build a list of vowels up front:
                                      var vowels = new HashSet<char> { 'a', 'e', 'i', 'o', 'u' };
                                  
                                      Console.WriteLine("Enter a Sentence");
                                      string sentence = Console.ReadLine().ToLower();
                                  
                                      int total = sentence.Count(c => vowels.Contains(c));
                                      Console.WriteLine("Your total number of vowels is: {0}", total);
                                      Console.ReadLine();
                                  }
                                  

                                  【讨论】:

                                  • 如果你不区分大小写可能会更好一些。并为初学者提供LINQ 的链接。
                                  • [i] 将句子分成一个字符数组来检查每个字符而不是整个句子?
                                  • @Phorden 否 - 字符串有一个索引器,它返回一个字符而不将其转换为数组。
                                  • @Souvlaki 它已经不区分大小写了——原来的帖子使用了ToLower,我保留了它;)
                                  • @ChaseFlorell 不需要 - string sentence = Console.ReadLine().ToLower(); "sentence" 在那时已经保证小写。
                                  猜你喜欢
                                  • 2020-03-24
                                  • 1970-01-01
                                  • 2012-02-29
                                  • 2015-05-16
                                  • 2011-05-05
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 1970-01-01
                                  相关资源
                                  最近更新 更多