wordcount

两年以后,再写一次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循环剔除不是字母的成分,然后读取字母组成一个单词。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值