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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Replacing JSON With Protobuf in Your Microservice Mesh: A Zero-Downtime Migration Blueprint
  • DataWeave: Play With Dates (Part 1)
  • Tired of Messy Code? Master the Art of Writing Clean Codebases
  • The Long Road to Java Virtual Threads

Trending

  • Microsoft Fabric Throttling: Diagnose Before You Scale
  • Prompt Caching for LLMs, Part 1: Exact-Match Caching in Production
  • Prompt Caching for LLMs, Part 2: Semantic Caching in Production
  • As AI Agents Multiply, Repository Access Could Become an Infrastructure Problem

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
Jul. 12, 18 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
25.9K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

  • Replacing JSON With Protobuf in Your Microservice Mesh: A Zero-Downtime Migration Blueprint
  • DataWeave: Play With Dates (Part 1)
  • Tired of Messy Code? Master the Art of Writing Clean Codebases
  • The Long Road to Java Virtual Threads

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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