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
- G -2
- O-2
- L- 1
- E-1
Input: MOON
Output
- M-1
- O-2
- 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.
- How to Reverse Number in C#
- How to Reverse a String in C#
- Palindrome String Program in C#
- Palindrome Number in C#
- How to Reverse Order of the Given String
- How To Reverse Each Word Of Given String
- 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
Let's try again with 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.