C# program to count the occurrences of each character


Firstly, set the string −

string str = "Website";
Console.WriteLine("String: "+str);

Check for every character in the string and increment a variable that would count the number of occurrences of that character −

for (int j = 0; j < str.Length; j++) {
   if (str[0] == str[j]) {
      cal++;
   }
}

Example

You can try to run the following code to count the occurrences of each character.

Live Demo

using System;
public class Demo {
   public static void Main() {
      string str = "Website";
      Console.WriteLine("String: "+str);
      while (str.Length > 0) {
         Console.Write(str[0] + " = ");
         int cal = 0;
         for (int j = 0; j < str.Length; j++) {
            if (str[0] == str[j]) {
               cal++;
            }
         }
         Console.WriteLine(cal);
         str = str.Replace(str[0].ToString(), string.Empty);
      }
      Console.ReadLine();
   }
}

Output

String: Website
W = 1
e = 2
b = 1
s = 1
i = 1
t = 1

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 19-Jun-2020

18K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements