• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms

Tuesday, August 11, 2020

Character Occurrence in a String in C# with Examples

 Admin     August 11, 2020     C#, Interview Question, Programming, Programs     No comments   

In this article, I am going to discuss the Character Occurrence in a String in C# program with some examples. Please read our previous article where we discussed the Binary to Decimal Conversion Program in C# with some examples. This is one of the most frequently asked interview questions in the interview. Here as part of this article, we are going to discuss the following mechanisms to count the character occurrences in a string.
  1. Using Loop to Count the Character Occurrence in a String.
  2. How to use Dictionary to Count the Number of Occurrences of character in C#.
  3. Using LINQ Group By method to count character occurrences.
Using Loop to Count the Character Occurrence in a String in C#:
Here in the following program, we take the input from Console and then remove the blank spaces from the input if any. Check the length of the input message and if it is greater than 0, then using for loop we calculate the number of occurrences of each character,
using System;
namespace LogicalProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter the string : ");
            string message = Console.ReadLine();
            //Remove the empty spaces from the message
            message = message.Replace(" ", string.Empty);
            
            while (message.Length > 0)
            {
                Console.Write(message[0] + " : ");
                int count = 0;
                for (int j = 0; j < message.Length; j++)
                {
                    if (message[0] == message[j])
                    {
                        count++;
                    }
                }
                Console.WriteLine(count);
                message = message.Replace(message[0].ToString(), string.Empty);
            }
            Console.ReadKey();
        }
    }
}
Output:
Using Loop to Count the Character Occurrence in a String in C#

Using Dictionary to Count the Number of Occurrences of character in C#:
In the below program, we created a dictionary to store each character and its count. We take the input message from the console and then loop through each character of the input message. For each character, we check whether that character already there in the dictionary or not. If already there then just increased its count by 1 else add that character to the dictionary with count as 1.
using System;
using System.Collections.Generic;
namespace LogicalProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter the string : ");
            string message = Console.ReadLine();
            Dictionary<char, int> dict = new Dictionary<char, int>();
            foreach (char ch in message.Replace(" ", string.Empty))
            {
                if (dict.ContainsKey(ch))
                {
                    dict[ch] = dict[ch] + 1;
                }
                else
                {
                    dict.Add(ch, 1);
                }
            }
            foreach (var item in dict.Keys)
            {
                Console.WriteLine(item + " : " + dict[item]);
            }
            Console.ReadKey();
        }
    }
}
Output:
Using Dictionary to Count the Number of Occurrences of character in C#

Using LINQ Group By method to count character occurrences in C#:
In the following program, we take the input message from the console and replace the blank spaces with an empty string. Then we use Linq Group By method to group each character and convert the result into a dictionary where the character is the key and the number of counts is its value.
using System;
using System.Collections.Generic;
using System.Linq;
namespace LogicalProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter the string : ");
            string message = Console.ReadLine();
            Dictionary<char, int> dict = message.Replace(" ", string.Empty)
                                         .GroupBy(c => c)
                                         .ToDictionary(gr => gr.Key, gr => gr.Count());
            foreach (var item in dict.Keys)
            {
                Console.WriteLine(item + " : " + dict[item]);
            }
            Console.ReadKey();
        }
    }
}
Output:
Using LINQ Group By method to count character occurrences

In the next article, I am going to discuss how to reverse a string in C# with and without using a built-in function. Here, in this article, I try to explain the different mechanisms to find the count of each character in a string.

Summary:
I hope this post will be helpful to write a program to find Character Occurrence in a String in C#
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post

0 comments:

Post a Comment

If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • What is Dependency Injection(DI)
    Hi friends! Today we are going to learn about Dependency Injection and in our last session we have come across Static classes and where it s...
  • C# Programming Examples on Sorting
    Today i am going to tell you some of the Sorting programming questions in C#. Q1- Write a C# program to perform Selection sort. Ans:  Sel...
  • Calling Web API Service in a Cross-Domain Using jQuery AJAX
    In this article, I am going to discuss Calling Web API Service in a Cross-Domain Using jQuery AJAX . Please read our previous article befor...
  • ViewBag in ASP.NET Core MVC
    In this article, I am going to discuss the use of ViewBag in ASP.NET Core MVC application with examples. Please read our previous article ...
  • Recursion And Back Tracking
    In this article, I am going to discuss Recursion And BackTracking in detail. Please read our previous article where we discussed Master Th...
  • What is Abstract Class and When we should use Abstract Class
    Hi friends! In our previous sessions we have seen  Difference Between Class and Struct . And in our last session  we learnt Usability of Sec...
  • Binary to Decimal Conversion in C# with Examples
    In this article, I am going to discuss the Binary to Decimal Conversion in C# with some examples. Please read our previous article where w...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape