Home >Backend Development >C#.Net Tutorial >C# program to count vowels in string

C# program to count vowels in string

WBOY
WBOYforward
2023-09-18 23:13:02673browse

C# 程序计算字符串中的元音

You need to check for vowels and consonants, but don't forget to check for upper and lower case.

To count vowels, check the "aeiou" characters individually, i.e.

if (myStr[i] == 'a' || myStr[i] == 'e' || myStr[i] == 'i' || myStr[i] == 'o' || myStr[i] == 'u' || myStr[i] == 'A' || myStr[i] == 'E' || myStr[i] == 'I' || myStr[i] == 'O' || myStr[i] == 'U') {
   vowel_count++;
}

Example

Here is the code to count the number of vowels in a string.

Live Demo

using System;
public class Demo {
   public static void Main() {
      string myStr;
      int i, len, vowel_count, cons_count;
      myStr = "Avengers";
      vowel_count = 0;
      cons_count = 0;
      // find length
      len = myStr.Length;
      for(i=0; i<len; i++) {
         if(myStr[i] ==&#39;a&#39; || myStr[i]==&#39;e&#39; || myStr[i]==&#39;i&#39; || myStr[i]==&#39;o&#39; || myStr[i]==&#39;u&#39; || myStr[i]==&#39;A&#39; || myStr[i]==&#39;E&#39; || myStr[i]==&#39;I&#39; || myStr[i]==&#39;O&#39; || myStr[i]==&#39;U&#39;) {
            vowel_count++;
         } else {
            cons_count++;
         }
      }
      Console.Write("Vowels in the string: {0}", vowel_count);
   }
}

Output

Vowels in the string: 3

The above is the detailed content of C# program to count vowels in string. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete