C# program to get max occurred character in a String


To get the maximum occurred character in a string, loop until the length of the given string and find the occurrence.

With that, set a new array to calculate −

for (int i = 0; i < s.Length; i++)
   a[s[i]]++;
}

The values we used above −

String s = "livelife!";
int[] a = new int[maxCHARS];

Now display the character and the occurrence −

for (int i = 0; i < maxCHARS; i++)
   if (a[i] > 1) {
      Console.WriteLine("Character " + (char) i);
      Console.WriteLine("Occurrence = " + a[i] + " times");
   }

Let us see the complete code −

Example

 Live Demo

using System;

class Program {

   static int maxCHARS = 256;

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

   public static void Main() {
      String s = "livelife!";
      int[] a = new int[maxCHARS];
      display(s, a);
   
      for (int i = 0; i < maxCHARS; i++)
      if (a[i] > 1) {
         Console.WriteLine("Character " + (char) i);
         Console.WriteLine("Occurrence = " + a[i] + " times");
      }
   }
}

Output

Character e
Occurrence = 2 times
Character i
Occurrence = 2 times
Character l
Occurrence = 2 times

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 22-Jun-2020

495 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements