How to obtain the highest occurring character in a String using C#?


The highest occurring character in a string is one that occurs most number of times. This can be demonstrated using the following example.

String: apples are red
The highest occurring character in the above string is e as it occurs 3 times, which is more than the occurrence of any other character.

A program that obtains the highest occurring character in a string using C# is given as follows.

Example

 Live Demo

using System;
namespace charCountDemo {
   public class Example {
      public static void Main() {
         String str = "abracadabra";
         int []charCount = new int[256];
         int length = str.Length;
         for (int i = 0; i < length; i++) {
            charCount[str[i]]++;
         }
         int maxCount = -1;
         char character = ' ';
         for (int i = 0; i < length; i++) {
            if (maxCount < charCount[str[i]]) {
               maxCount = charCount[str[i]];
               character = str[i];
            }
         }
         Console.WriteLine("The string is: " + str);
         Console.WriteLine("The highest occurring character in the above string is: " + character);
         Console.WriteLine("Number of times this character occurs: " + maxCount);
      }
   }
}

Output

The output of the above program is as follows.

The string is: abracadabra
The highest occurring character in the above string is: a
Number of times this character occurs: 5

Now, let us understand the above program.

The string str is abracadabra. A new array charCount is created which is of size 256 and shows all the characters in the ASCII table. Then the string str is traversed using a for loop and the value in charCount is incremented corresponding to the character in the string. This can be seen in the following code snippet.

String str = "abracadabra";
int []charCount = new int[256];
int length = str.Length;
for (int i = 0; i < length; i++) {
   charCount[str[i]]++;
}

The integer maxCount stores the maximum count and character is the char value that occurs the maximum times. The values of maxCount and character can be determined using a for loop. This can be seen in the following code snippet.

int maxCount = -1;
char character = ' ';
for (int i = 0; i < length; i++) {
   if (maxCount < charCount[str[i]]) {
      maxCount = charCount[str[i]];
      character = str[i];
   }
}

Finally, the values of str, maxCount and character are displayed. This can be seen in the following code snippet.

Console.WriteLine("The string is: " + str);
Console.WriteLine("The highest occurring character in the above string is: " + character);
Console.WriteLine("Number of times this character occurs: " + maxCount);

Updated on: 26-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements