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

Basic C# Code to Find Out the Occurrence of Each Character in a String

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

Classify programming languages: Build a model that predicts a code's programming language based on its text.  Content provided by IBM Developer. 

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");
            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.

Image title

In this way, we can find the number of times each character occurred in a string.

Start coding something amazing with our library of open source Cloud code patterns. Content provided by IBM.

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

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}