题目:编写一个程序,对一个文本文件进行分析,将不同单词的个数按大小排序,并输出该文件中每个不同单词在文本中出现的次数
例如:To be or not to be, that is the question.Whether in the mind to stuffer
应输出:to 3次,be 2次, or 1次
思路:
当前测试环境:开发工具xcode Version 10.1 (10B61),操作系统Macos 10.14.3
注意:由于stricmp不能使用,已被废弃,所以使用strcasecmp功能是一样的
代码中内存申请没有释放,排序效率低。
当文件中内容以字母结束时,在readwords函数后面加上判断,if(pre == 0 || current ==0)tmp[i]=' '; 最后再加入到pw中
1 #include <stdio.h> 2 #include <strings.h> 3 #include <stdlib.h> 4 #include <xlocale.h> 5 6 struct myString 7 { 8 int count;//单词出现重复次数 9 char *_str; 10 }; 11 struct words 12 { 13 int num; //当前存储单词个数 14 struct myString str[1024]; 15 }; 16 void readWords(struct words *pw) 17 { 18 FILE *fp = fopen("book.txt","r"); 19 if(fp == NULL) 20 { 21 printf("文件打开出错... "); 22 exit(0); 23 } 24 pw->num=0; 25 char ch = getc(fp); 26 char tmp[30] = {0}; 27 int i = 0; 28 int pre = 0; // 前一个字符是字母 29 int current = 0;//当前字符是字母 30 while(ch != EOF) 31 { 32 if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ) 33 { 34 current = 0; 35 //如果前一个不是字母,当前是字母 36 if(pre == -1 && current == 0) 37 { 38 i = 0; 39 tmp[i]=ch; 40 } 41 else if(pre == 0 && current == 0)//如果前一个是字母,且当前是字母 42 { 43 tmp[i] = ch; 44 } 45 ++i; 46 } 47 else 48 { 49 current = -1; 50 //如果前一个是字母,当前不是字母 51 if(pre == 0 && current == -1) 52 { 53 tmp[i] = '