数组实现
#include <stdio.h>#include<stdlib.h>#include<math.h>#include<string.h>#include<stdbool.h>char up_to_low(char c) { // 转换大小写if ((c >= 'A') && (c <= 'Z')) {return (c+32);}return c;}bool is_alp(char c) {if ((c >= 'a') && (c <= 'z'))return true;return false;}void process() {int i = 0;int j = 0;char str[100] = { 0 };char* str_ptr[100]; // 指针数组,每个指针指向不重复的词int fre_array[100] = { 0 }; // 统计对应词频char vocabulary[100][15] = { 0 }; // 分割词汇int begin = 0;int end = 0;int count = 0; // 统计所有单词数int flag = 0; // 用于记录单词开头int dic_count = 0; // 统计不重复的词的数量int sign = 1;for (i = 0; i < 100; i++) str_ptr[i] = NULL;for (i = 0; i < 100; i++)fre_array[i] = 1;i = 0;while ((str[i++] = up_to_low(getchar()))!= EOF); // 读入字符串i = 0;while (str[i]) { // 分割字符串if (is_alp(str[i])&&(flag==0)) {begin = i;flag = 1;}if (is_alp(str[i]) && (!is_alp(str[i + 1]))) {end = i;for (j = 0; j < end - begin+1; j++) {vocabulary[count][j] = str[begin + j];}count++;flag = 0;}i++;}for (i = 0; i < count; i++) { // 查找for (j = 0; j < dic_count; j++) {if (strcmp(vocabulary[i], str_ptr[j]) == 0) { // 如果出现则对应的值+1fre_array[j]+= 1;sign = 0;}}if (sign) { // 如果未出现,指针数组指向该新的词汇str_ptr[dic_count]= vocabulary[i];dic_count++;}}int max = 0;for (i = 1; i < dic_count; i++) {if ((fre_array[i]>fre_array[max])) max = i;if ((fre_array[i] == fre_array[max])&& (strcmp(str_ptr[i],str_ptr[max])>0)) max=i;}printf("%s %d", str_ptr[max], fre_array[max]);}int main() {process();return 0;}
