How To Count Occurrence Of Each Character From The String In C#

Introduction

In this article, we will explore How to count the occurrence of each character in the string in C#.

Below are a few examples of inputs and Outputs.

Examples

Input: GOOGLE

Output

  1. G -2
  2. O-2
  3. L- 1
  4. E-1

Input: MOON

Output

  1. M-1
  2. O-2
  3. N-1

This is an essential technical interview question that may be posed to beginner, intermediate, and experienced candidates.

We previously covered the topics below.

  1. How to Reverse Number in C#
  2. How to Reverse a String in C#
  3. Palindrome String Program in C#
  4. Palindrome Number in C#
  5. How to Reverse Order of the Given String
  6. How To Reverse Each Word Of Given String
  7. How To Remove Duplicate Characters From String In C#

Let’s start,

Console.WriteLine("Enter a String");
var str = Console.ReadLine();

Dictionary<char, int> keyValuePairs = new Dictionary<char, int>();

for (int i = 0; i < str.Length; i++)
{
    if (!keyValuePairs.ContainsKey(str[i]))
    {
        keyValuePairs.Add(str[i], 1);
    }
    else
    {
        keyValuePairs[str[i]] = keyValuePairs[str[i]] + 1;
    }
}

foreach (var item in keyValuePairs)
{
    Console.WriteLine($"Char: {item.Key}, Count: {item.Value}");
}

Console.ReadLine();

Output

Output

Let's try again with different input.

Different input

We have learned how to count the occurrence of each character in the string. I hope you find this article enjoyable and useful.


Recommended Free Ebook
Similar Articles