C# Program to find number of occurrence of a character in a String


Let’s say our string is −

String s = "mynameistomhanks";

Now create a new array and pass it a new method with the string declared above. This calculates the occurrence of characters in a string.

static void calculate(String s, int[] cal) {
   for (int i = 0; i < s.Length; i++)
   cal[s[i]]++;
}

Let us see the complete code.

Example

 Live Demo

using System;
class Demo {
   static int maxCHARS = 256;
   static void calculate(String s, int[] cal) {
      for (int i = 0; i < s.Length; i++)
      cal[s[i]]++;
   }
   public static void Main() {
      String s = "mynameistomhanks";
      int[] cal = new int[maxCHARS];
      calculate(s, cal);
      for (int i = 0; i < maxCHARS; i++) {
         if (cal[i] > 1) {
            Console.WriteLine("Character " + (char) i);
            Console.WriteLine("Occurrence = " + cal[i] + " times");
         }
         if (cal[i] == 1) {
            Console.WriteLine("Character " + (char) i);
            Console.WriteLine("Occurrence = " + cal[i] + " time");
         }
      }
   }
}

Output

Character a
Occurrence = 2 times
Character e
Occurrence = 1 time
Character h
Occurrence = 1 time
Character i
Occurrence = 1 time
Character k
Occurrence = 1 time
Character m
Occurrence = 3 times
Character n
Occurrence = 2 times
Character o
Occurrence = 1 time
Character s
Occurrence = 2 times
Character t
Occurrence = 1 time
Character y
Occurrence = 1 time

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 22-Jun-2020

530 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements