C# Program to Count Number of Vowels and Consonants in a Given String
Last Updated :
07 Jan, 2022
C# is a general-purpose programming language it is used to create mobile apps, desktop apps, web
sites, and games. As we know that a, e, i, o, u are vowels, and the remaining alphabet is known as a consonant in English so now using C# language we will create a program that will return us the total number of vowels and consonants present in the given string.
Example:
Input: geeksforgeeks
Output: Total number of vowels = 5
Total number of consonants = 8
Input: HelloGFG
Output: Total number of vowels = 2
Total number of consonants = 6
Approach:
To print the total number of Vowels and consonants from a given String we use the following approach:
- Store the string using string datatype.
- Declare two variables to count the number of vowels and consonants.
- Now using the length property find the length of the given string
- Now iterate the string from left to right and check if the character is either vowel or a consonant.
- If the character encountered is a vowel increase the count of vowel else increases the count of consonant.
Example 1:
C#
using System;
class GFG{
public static void Main()
{
string inputstring;
int i, len, vowels, consonants;
inputstring = "geeksforgeeks" ;
vowels = 0;
consonants = 0;
len = inputstring.Length;
for (i = 0; i < len; i++)
{
if (inputstring[i] == 'a' || inputstring[i] == 'e' ||
inputstring[i] == 'i' || inputstring[i] == 'o' ||
inputstring[i] == 'u' || inputstring[i] == 'A' ||
inputstring[i] == 'E' || inputstring[i] == 'I' ||
inputstring[i] == 'O' || inputstring[i] == 'U' )
{
vowels++;
}
else if ((inputstring[i] >= 'a' && inputstring[i] <= 'z' ) ||
(inputstring[i] >= 'A' && inputstring[i] <= 'Z' ))
{
consonants++;
}
}
Console.WriteLine( "count of vowel = " + vowels);
Console.WriteLine( "count of consonant = " + consonants);
}
}
|
Output
count of vowel = 5
count of consonant = 8
Example 2:
C#
using System;
class GFG{
public static void Main()
{
char [] inputstring = new char [100];
int i, vowels, consonants, x;
vowels = 0;
consonants = 0;
Console.WriteLine( "Please enter the length of the string:\n" );
x = int .Parse(Console.ReadLine());
Console.WriteLine( "Enter string:\n" );
for (i = 0; i < x; i++)
{
inputstring[i] = Convert.ToChar(Console.Read());
}
for (i = 0; inputstring[i] != '\0' ; i++)
{
if (inputstring[i] == 'a' || inputstring[i] == 'e' ||
inputstring[i] == 'i' || inputstring[i] == 'o' ||
inputstring[i] == 'u' || inputstring[i] == 'A' ||
inputstring[i] == 'E' || inputstring[i] == 'I' ||
inputstring[i] == 'O' || inputstring[i] == 'U' )
{
vowels++;
}
else
{
consonants++;
}
}
Console.WriteLine( "\ncount of vowel = " + vowels);
Console.WriteLine( "count of consonant = " + consonants);
Console.ReadLine();
Console.ReadLine();
}
}
|
Output:
Please enter the length of the string:
6
Enter string:
HeyGFG
count of vowel = 1
count of consonant = 5
Share your thoughts in the comments
Please Login to comment...