user2845216
user2845216

Reputation: 19

How to Count Vowels in a sentence in Text File (C#)

I have to create a small program where I have to prompt the user for idioms and store these into a text file. After that, I have to open up the text file and count the number of individual vowels in each idiom (a, e, i, o, u) and display these to the user.

Here is the code I have created so far:

        int numberOfIdioms;
        string fileName = "idioms.txt";
        int countA = 0, countE = 0, countI = 0, countO = 0, countU = 0;

        Console.Title = "String Functions";

        Console.Write("Please enter number of idioms: ");
        numberOfIdioms = int.Parse(Console.ReadLine());

        string[] idioms = new string[numberOfIdioms];
        Console.WriteLine();

        for (int aa = 0; aa < idioms.Length; aa++)
        {
            Console.Write("Enter idiom {0}: ", aa + 1);
            idioms[aa] = Console.ReadLine();
        }

        StreamWriter myIdiomsFile = new StreamWriter(fileName);

        for (int a = 0; a < numberOfIdioms; a++)
        {
            myIdiomsFile.WriteLine("{0}", idioms[a]);
        }

        myIdiomsFile.Close();

Upvotes: 1

Views: 1624

Answers (3)

Rishu Ranjan
Rishu Ranjan

Reputation: 574

We can use regular expression to match vowels in each idoms. you can call the function mentioned below to get the vowel count.

working code snippet:

  //below function will return the count of vowels in each idoms(input)
 public static int GetVowelCount(string idoms)
   {
       string pattern = @"[aeiouAEIOU]+"; //regular expression to match vowels
       Regex rgx = new Regex(pattern);   
       return rgx.Matches(idoms).Count;
   }

Upvotes: 0

Szymon
Szymon

Reputation: 43023

You can use the following code to get the vowel count for a string:

int vowelCount = System.Text.RegularExpressions.Regex.Matches(input, "[aeoiu]").Count;

Replace input with your string variable.

If you want to count regardless of case (upper/lower), you can use:

int vowelCount = System.Text.RegularExpressions.Regex.Matches(input.ToLower(), "[aeoiu]").Count;

Upvotes: 4

arjthakur
arjthakur

Reputation: 61

string Target = "my name and your name unknown MY NAME AND YOUR NAME UNKNOWN";

List pattern = new List { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' };

int t = Target.Count(x => pattern.Contains(x));

Upvotes: 1

Related Questions