Counting Characters In A Given String Using C#

Introduction

This blog explains how we can count the characters of a given string, using C#. Many interviewers ask this question and ask freshers to write the program. We can write a program using C# like below.

Programs

  1. using System;  
  2. public class Program {  
  3.     public static void Main() {  
  4.         string strFirst;  
  5.         char charCout;  
  6.         int Count = 0;  
  7.         Console.Write("Enter Your String:");  
  8.         strFirst = Console.ReadLine();  
  9.         Console.Write("Enter Count Character:");  
  10.         charCout = Convert.ToChar(Console.ReadLine());  
  11.         Console.Write("Your Character Count:");  
  12.         foreach(char chr in strFirst) {  
  13.             if (chr == charCout) {  
  14.                 Count++;  
  15.             }  
  16.         }  
  17.         Console.Write(Count);  
  18.     }  
  19. }  

Conclusion

I hope this really helps the freshers in their interview, and also it should help those who are newly learning C# programming.