文章目录
两年以后,再写一次wordcount
1. 两年前写的代码
时光机
那时的我,稚嫩,连markdown都不知道。
两年前的代码
void readFile(char *path){
FILE *ori = fopen(path,"r");
FILE *tempFile = fopen("tempFile.txt","w");
char temp[1024];
while(!feof(fp)){
fscanf(ori,"%s",temp);
for(int i = 0; i < strlen(temp); i++){
if(!isLetter(temp[i])){
temp[i] = ' ';
}
}
fprintf(tempFile,"%s\n",temp);
}
}
这个思路是先将非字母替换成空格,然后写到一个临时文件中,然后打开临时文件,使用fscanf读取一个一个的字符串。思路也还不错。就是需要一个辅助文件。
2. 新的思路
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int isletter(char c) {
return islower(c) || isupper(c);
}
int wordcount(char const *str) {
int count = 0;
size_t i = 0, x;
char word[128];
while (str[i] != '\0') {
// 去除非字母
while (str[i] != '\0' && !isletter(str[i])) i++;
// 提取字母
x = 0;
while (str[i] != '\0' && isletter(str[i])) word[x++] = str[i++];
if (x > 0) {
// !!
word[x] = '\0';
printf("detect word: %s\n", word);
count++;
}
}
return count;
}
void run() {
FILE *fp = fopen("input.dat", "r");
if (!fp) {
exit(-1);
}
long total = 0;
int MAXLEN = 10240;
char line[MAXLEN];
while (1) {
char *ans = fgets(line, MAXLEN, fp);
if (!ans) break;
total += wordcount(line);
}
printf("===SUMMARY===\n");
printf("word number: %ld\n", total);
fclose(fp);
}
int main(void) {
run();
system("pause");
return 0;
}
提取一行内容中的单词时候,先用while循环剔除不是字母的成分,然后读取字母组成一个单词。