Q:

C# program to count the total number of vowels in a given string

belongs to collection: C# Basic Programs | String programs

0

C# program to count the total number of vowels in a given string

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

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# program to count the total number of vowels in a given 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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Basic Programs | String programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# program to generate random strings... >>
<< C# program to perform the right padding without us...