Home »
.Net »
C# Programs
C# - Count Vowels in a String
Learn, how to count the total number of vowels in a given string in C#?
Submitted by Nidhi, on October 13, 2020 [Last updated : March 21, 2023]
Here we read a string from the keyboard and then count the vowels ('a', 'e', 'i', 'o', 'u') in the specified string then print the count on the console screen.
C# program to count the total number of vowels in a given string
The source code to count the total number of vowels in a given string is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//C# - Count Vowels in a String.
using System;
class Demo
{
static int CountVowels(string str)
{
int i = 0;
int countVowels = 0;
for (i = 0; i<str.Length; i++)
{
if ((str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u') ||
(str[i] == 'A' || str[i] == 'E' || str[i] == 'I' || str[i] == 'O' || str[i] == 'U'))
countVowels++;
}
return countVowels;
}
public static void Main()
{
int vowels = 0;
string str = "";
Console.Write("Enter the string: ");
str = Console.ReadLine();
vowels=CountVowels(str);
Console.WriteLine("Total vowels are: "+vowels);
}
}
Output
Enter the string: www.includehelp.com
Total vowels are: 5
Press any key to continue . . .
Explanation
Here, we created a class Demo that contains two static methods CountVowels() and Main().
In the CountVowels(), we traversed the string character by character and check the character is a vowel, if any character found a vowel then we increase the value of the variable countVowels by 1, after traversing the complete string we returned the value of countVowels variable to the Main() method.
In the Main() method, we created a string str and then read a string from the user and passed the string str to the CountVowels() method that will return the count of vowels and then we printed the return value on the console screen.
C# Basic Programs »