Counting Occurrences of Vowels in a String Using Dictionary in C#

When working with strings in C#, you might come across scenarios where you need to analyze the frequency of certain characters, such as vowels. One effective way to accomplish this is by using a dictionary to count the occurrences of each vowel in a string. In this blog post, we will walk through the process of building a C# program to count the occurrences of vowels using a dictionary.

Why Use a Dictionary?

A dictionary in C# is a collection of key-value pairs. It is an excellent choice for this task because:

  • Efficiency: Dictionary operations like insertion and lookup are very fast.
  • Clarity: The code is easy to read and understand.

Step-by-step implementation

Let's break down the implementation into clear steps.

1. Setting up the Program

First, we need to set up a basic C# console application. Open your favorite C# development environment, create a new console application, and name it appropriately.

2. Reading the Input

We will prompt the user to enter a string, which will be processed to count the vowels.

 Vowels

By converting the input to lowercase, we ensure that the program is case-insensitive.

3. Initializing the Dictionary

Next, initialize a dictionary with vowels as keys and their counts set to zero.

Dictionary

4. Counting the Vowels

We will iterate through each character in the input string and update the counts in the dictionary.

Counting the Vowels

5. Displaying the Results

Finally, we will display the count of each vowel.

Displaying the Results

Complete Code

Here's the complete code for the program.

using System;
using System.Collections.Generic;
class Program
{
    static void Main()
    {
        Console.WriteLine("Enter a string:");
        string input = Console.ReadLine().ToLower();

        Dictionary<char, int> vowelCount = new Dictionary<char, int>
        {
            {'a', 0},
            {'e', 0},
            {'i', 0},
            {'o', 0},
            {'u', 0}
        };
        foreach (char c in input)
        {
            if (vowelCount.ContainsKey(c))
            {
                vowelCount[c]++;
            }
        }
        Console.WriteLine("Vowel counts:");
        foreach (var vowel in vowelCount)
        {
            Console.WriteLine($"{vowel.Key}: {vowel.Value}");
        }
    }
}

Running the Program

When you run the program, it will prompt you to enter a string. After entering the string, the program will output the count of each vowel. For example.

Enter a string:
Hello World
Vowel counts:
a: 0
e: 1
i: 0
o: 2
u: 0

Conclusion

Using a dictionary to count the occurrences of vowels in a string is both efficient and straightforward in C#. This approach can be extended to count other characters or to perform more complex text analysis. By understanding the basics of dictionaries and string manipulation, you can tackle a wide range of problems in C#. Happy coding!