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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | #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'