Here Input string = “test string for testing”
Construct the character count array from the input string.
iCount[‘e’] = 2
iCount[‘s’] = 3
iCount[‘t’] = 5
iCount[‘r’] = 2
iCount[‘i’] = 2
iCount[‘f’] = 1
iCount[‘o’] = 1
iCount[‘f’] = 1
iCount[‘n’] = 2
iCount[‘g’] = 1
In the above array, we can get the maximum number is ‘5’ that is ‘t’
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 |
#include <stdio.h> #define TOTAL_CHAR 256 // Max characters allowed int main() { int iCount[TOTAL_CHAR]; int max=0; int ascii=0; //sample string char pchStr[] = "test string for testing"; /* Initializes the frequency of all characters to 0 */ for(int i=0; i<TOTAL_CHAR; i++) { iCount[i] = 0; } /* Finds frequency of each characters */ int index=0; while(pchStr[index] != '\0') { ascii = (int)pchStr[index]; iCount[ascii]++; index++; } max = 0; /* Finds the maximum frequency character */ for(int i=0; i<TOTAL_CHAR; i++) { if(iCount[i] > iCount[max]) max = i; } printf("Maximum occurring character is '%c' = %d times.", max, iCount[max]); return 0; } |
1 |
Maximum occurring character is 't' = 5 times. |
Recommended Tutorials for this example is: