C# program to count the occurrences of each character in a String

Understanding the Problem:

Before we start writing code, it’s crucial to understand the problem at hand. 

We want to create a C# program that takes a string as input and produces a count of each unique character in that string

Code Example 1: Program to find Character Occurrence in a String in C#

Let’s start with a simple approach using a dictionary to store character occurrences.

Below is the C# program to count the occurrences of each character in a String.

using System;
using System.Collections.Generic;

class CharacterCounter
{
    static void Main()
    {
        string inputString = "hello world";
        Dictionary<char, int> charCount = new Dictionary<char, int>();

        foreach (char c in inputString)
        {
            // Exclude spaces from character count
            if (c != ' ')
            {
                if (charCount.ContainsKey(c))
                    charCount++;
                else
                    charCount = 1;
            }
        }

        // Display the results
        foreach (var entry in charCount)
        {
            Console.WriteLine($"Character '{entry.Key}' occurs {entry.Value} times.");
        }
    }
}

Output:

Character 'h' occurs 1 times.
Character 'e' occurs 1 times.
Character 'l' occurs 3 times.
Character 'o' occurs 2 times.
Character 'w' occurs 1 times.
Character 'r' occurs 1 times.
Character 'd' occurs 1 times.

Code Explanation:

  • We use a Dictionary<char, int> to store characters and their corresponding counts.
  • The foreach loop iterates through each character in the input string.
  • We check if the character is already a key in the dictionary. If yes, we increment its count; otherwise, we add it with a count of 1.
  • Finally, we iterate through the dictionary to display the results.

Code Example 2: Count occurrences of each character Using LINQ

In the below code example, we will count each unique character in the string using LINQ (Language Integrated Query).

using System;
using System.Linq;

class CharacterCounter
{
    static void Main()
    {
        string inputString = "hello world";
        
        var charCount = inputString
            .Where(c => c != ' ') // Exclude spaces
            .GroupBy(c => c)
            .ToDictionary(g => g.Key, g => g.Count());

        // Display the results
        foreach (var entry in charCount)
        {
            Console.WriteLine($"Character '{entry.Key}' occurs {entry.Value} times.");
        }
    }
}

Code Explanation:

  • We use LINQ’s GroupBy to group characters and then ToDictionary to create our character count dictionary.
  • This approach is more concise and often preferred by most of the developers.

Example 3: Using a Char Array

We will use a character array to iterate through the string and update the character count.

In the below code example, we will find the Character Occurrence in a String in C#.

using System;

class CharacterCounter
{
    static void Main()
    {
        string inputString = "Hello World";
        // Remove empty spaces from the string
        inputString = inputString.Replace(" ", string.Empty);
        int[] charCount = new int[256]; // Assuming ASCII characters

        foreach (char c in inputString)
        {
            charCount++;
        }

        // Display the results
        for (int i = 0; i < 256; i++)
        {
            if (charCount[i] > 0)
            {
                Console.WriteLine($"Character '{(char)i}' occurs {charCount[i]} times.");
            }
        }
    }
}

Output:

Character 'H' occurs 1 times.
Character 'W' occurs 1 times.
Character 'd' occurs 1 times.
Character 'e' occurs 1 times.
Character 'l' occurs 3 times.
Character 'o' occurs 2 times.
Character 'r' occurs 1 times.

Code Explanation:

  • We use an integer array of size 256 to represent ASCII characters.
  • The array is initialized to zeros.
  • We iterate through the input string, and for each character, we increment the corresponding index in the array.
  • Finally, we iterate through the array to display non-zero counts.

Programs you might also like:

Shekh Ali
5 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments