Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

DZone's Guide to

# 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#.

· Web Dev Zone ·
Free Resource

Comment (1)

Save
{{ articles[0].views | formatCount}} Views

Access over 20 APIs and mobile SDKs, up to 250k transactions free with no credit card required

Recently 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");
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());
}

}``````

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.

#1 for location developers in quality, price and choice, switch to HERE.

Topics:
c# ,algorithm ,string ,web dev ,tutorial

Comment (1)

Save
{{ articles[0].views | formatCount}} Views

Opinions expressed by DZone contributors are their own.