DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • DataWeave: Play With Dates (Part 1)
  • Tired of Messy Code? Master the Art of Writing Clean Codebases
  • The Long Road to Java Virtual Threads
  • Exploring Exciting New Features in Java 17 With Examples

Trending

  • AWS Kiro: The Agentic IDE That Makes Specs the Unit of Work
  • Beyond Conversation: Mastering Context with Claude Code Skills and Agents
  • Spring Boot Done Right: Lessons From a 400-Module Codebase
  • Comparing Top Gen AI Frameworks for Java in 2026
  1. DZone
  2. Data Engineering
  3. Data
  4. Basic C# Code to Find Out the Occurrence of Each Character in a String

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

By 
Debendra Dash user avatar
Debendra Dash
·
Jul. 12, 18 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
25.7K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Strings Data Types

Opinions expressed by DZone contributors are their own.

Related

  • DataWeave: Play With Dates (Part 1)
  • Tired of Messy Code? Master the Art of Writing Clean Codebases
  • The Long Road to Java Virtual Threads
  • Exploring Exciting New Features in Java 17 With Examples

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook