【创作赢红包】C语言统计txt文件中单词的个数

你可以参考以下代码来统计txt文件中单词的个数:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define MAX_WORD_LEN 50

int main() {
    FILE *fp;
    char word[MAX_WORD_LEN];
    int count = 0;

    fp = fopen("test.txt", "r");
    if (fp == NULL) {
        printf("Error opening file\n");
        exit(1);
    }

    while (fscanf(fp, "%s", word) == 1) {
        // 将单词中的大写字母转换为小写字母
        for (int i = 0; i < strlen(word); i++) {
            word[i] = tolower(word[i]);
        }
        count++;
    }

    printf("The number of words in the file is %d\n", count);

    fclose(fp);
    return 0;
}

该程序首先打开一个名为`test.txt`的文件,然后读取文件中的每个单词,并将单词中的大写字母转换为小写字母。最后统计单词的数量并输出。

需要说明的是,该程序中假设一个单词的长度不超过50个字符。如果实际情况中可能出现更长的单词,需要相应地增加`MAX_WORD_LEN`的值。

此外,该程序中忽略了单词之间的标点符号和空格,这意味着程序会把`"hello,"`和`"hello"`视为不同的单词。如果需要对标点符号和空格进行处理,可以使用字符串处理函数`strtok()`或正则表达式等技术。

如果要在程序中处理标点符号和空格,可以使用字符串处理函数`strtok()`。具体实现如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define MAX_WORD_LEN 50

int main() {
    FILE *fp;
    char line[100];
    char *token;
    char word[MAX_WORD_LEN];
    int count = 0;

    fp = fopen("test.txt", "r");
    if (fp == NULL) {
        printf("Error opening file\n");
        exit(1);
    }

    while (fgets(line, sizeof(line), fp)) {
        // 分割每行字符串
        token = strtok(line, " \t\n\r.,;:\"\'()[]{}|<>?!@#$%^&*+-=/\\");
        while (token != NULL) {
            // 处理每个单词
            strncpy(word, token, MAX_WORD_LEN - 1);
            word[MAX_WORD_LEN - 1] = '\0';
            for (int i = 0; i < strlen(word); i++) {
                word[i] = tolower(word[i]);
            }
            count++;
            token = strtok(NULL, " \t\n\r.,;:\"\'()[]{}|<>?!@#$%^&*+-=/\\");
        }
    }

    printf("The number of words in the

文件 is %d\n", count);

    fclose(fp);
    return 0;
}

在上述程序中,使用`strtok()`函数分割每行字符串。`strtok()`函数的第一个参数为要分割的字符串,第二个参数为分割字符集合,即将要被分割的字符。在该程序中,分割字符集合包含了空格、制表符、回车、换行以及各种标点符号。

在处理每个单词时,使用`strncpy()`函数将单词复制到`word`数组中,并在单词的末尾添加`\0`,使其成为一个C字符串。然后使用`tolower()`函数将单词中的大写字母转换成小写字母,以便进行大小写不敏感的统计。

最后,每次处理一个单词时,将计数器`count`加1。程序运行完毕后,计数器`count`的值即为文件中单词的数量。

猜你喜欢

转载自blog.csdn.net/qq_50942093/article/details/129908614