C# Count Vowels

后端 未结 17 1771
小鲜肉
小鲜肉 2020-12-03 08:59

I am learning to program C# and I am trying to count the vowels. I am getting the program to loop through the sentence, but instead of returning vowel count, it is just retu

17条回答
  •  北荒
    北荒 (楼主)
    2020-12-03 09:27

    Since Reed has answered your question, I will offer you another way to implement this. You can eliminate your loop by using LINQ and lambda expressions:

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

    If you don't understand this bit of code, I'd highly recommend looking up LINQ and Lambda Expressions in C#. There are many instances that you can make your code more concise by eliminating loops in this fashion.

    In essence, this code is saying "count every character in the sentence that is contained within the string "aeiou". "

提交回复
热议问题