In this tutorial, we will write a program in C to find the maximum occurring character in a string. Before that, you may go through the following topics in C
Find maximum occurring character in a string in C
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_size 100 //MAX string size
#define MAX_char 255 //MAX character number
void main()
{
char str[MAX_size];
int freq[MAX_char];
int i = 0, max;
int ascii;
printf("Enter the string : ");
fgets(str, sizeof str, stdin);
for (i = 0; i < MAX_char; i++)
{
freq[i] = 0;
}
//calculating the frequency
i = 0;
while (str[i] != '\0')
{
ascii = (int) str[i];
freq[ascii] += 1;
i++;
}
max = 0;
for (i = 0; i < MAX_char; i++)
{
if (i != 32)
{
if (freq[i] > freq[max])
max = i;
}
}
printf("\nCharacter with highest frequency is: '%c'", max);
printf("\nAnd the number of times, it appears is: '%d'", freq[max]);
}
Output:
Enter the string : Welcome to simple2code
Character with highest frequency is: 'e'
And the number of times, it appears is: '4'