• 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

  • How to Implement DELETE Method in Web API
    In this article, I am going to discuss how to Implement DELETE Method in Web API Application with an example. Please read our previous art...
  • HTTP Client Message Handler in Web API
    In this article, I am going to discuss HTTP Client Message Handler in Web API with real-time examples. As we already discussed in HTTP Mes...
  • Cross-Origin Resource Sharing in WEB API
    In this article, I am going to discuss how to enable Cross-Origin Resource Sharing in Web API which allows cross-domain AJAX calls. Pleas...
  • ASP.NET Web API Basic Authentication
    In this article, I am going to discuss how to implement the ASP.NET Web API Basic Authentication step by step with an example. Please read...
  • Development Approach with Entity Framework
    In this article, I will discuss Development Approach with Entity Framework . The entity framework provides three different approaches when ...
  • Views in ASP.NET Core MVC
    In this article, I am going to discuss Views in the ASP.NET Core MVC application. Please read our previous article before proceeding to th...
  • Introduction to Entity Framework
    Before .NET 3.5 as a developer, we often used to write ADO.NET code to perform CRUD operation with the underlying database. For this, we ne...

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