Basic C# Code to Find Out the Occurrence of Each Character in a String
A common test for devs is to count the amount of times of character appears in a string. In this post, we go over how to do so using C#.
Join the DZone community and get the full member experience.
Join For FreeRecently I went to an interview where the interviewer asked me to write some basic code to find out the occurrence of each character in a string.
I managed to do that using some loop, but it was not an optimal solution. The complexity, O(n), for that code was fairly high. I've continued to play with the code since, and have found a lot of options to solve this problem.
I ended up using the GroupBy
clause of Linq to solve this problem.
Problem Statement:
Given a string like this — "This is Debendra Dash Solution" — we need to find out how many characters repeated and how many times they were repeated.
static void Main(string[] args)
{
Console.WriteLine("enter a string");
string name = Console.ReadLine();
Program p = new Program();
Dictionary<char, int> dict = new Dictionary<char, int>();
dict = p.getCount(name);
foreach(KeyValuePair<char, int> pair in dict)
{
Console.WriteLine(pair.Key.ToString() + " - " + pair.Value.ToString());
}
Console.ReadLine();
}
Now here is the main logic using Linq to find out the occurrence of each character in the string.
public Dictionary<char,int> getCount(string name)
{
return name.GroupBy(x => x).ToDictionary(gr => gr.Key, gr => gr.Count());
}
Code Explanation
GroupBy: This method transforms a collection into groups. Each group has a key. With this method from the System.Linq namespace, you can apply grouping to many collections.
Once the value is grouped, we will put them in a dictionary and use this key-value pair to retrieve the data.
In this way, we can find the number of times each character occurred in a string.
Opinions expressed by DZone contributors are their own.
Comments