統計字串中出現次數最多的字母並輸出
阿新 • • 發佈:2019-01-31
/* *input:tester *output:e */ #include<stdio.h> #include<stdlib.h> //統計字串中出現次數最多的字母,如果字母出現次數相同,則按a-z字典序輸出第一個。 int countCharacter(const char * str) { int i=0,max=str[0]-'a'; int num[26]={0}; while(str[i] != '\0') { int x = str[i]-'a'; num[x]++; if(num[x] > num[max]) { max=x; i++; }else if(num[x] == num[max] && x < max){ max=x; i++; }else{ i++; } } return max; } int main() { int re; const char *str = (char *)malloc(sizeof(char)*100); printf("input:"); scanf("%s",str); re = countCharacter(str); printf("output:%c\n",'a'+re); return 0; }