我正在编写一个程序,该程序将文本文件作为输入并输出每个单词出现的次数。为此,我使用的是链接列表,但是每当我打印列表时,仅打印每行的最后一个单词。下面的代码显示了如何将每个单词添加到列表中:

while(fgets(line, sizeof(line), fp)) {
    LIST *node = malloc(sizeof(LIST));
    token = strtok(line, delim);

    while (token != NULL) {
        if (search(head, token)) {
            node->count += 1;
        } else {
            node->string = strdup(token);
            node->count = 1;
            node->next =NULL;
        }

        token = strtok(NULL, delim);
    }

    if (head == NULL) {
        current = head = node;
    } else {
        current = current->next = node;
    }
}


行初始化为:char * line [128];如果单词已经在列表中,则search()返回true,否则返回false,因此如果单词已存在,则计数增加。
   这是我打印的位置:

for (current = head; current ; current = current->next) {
     current->string = strtok(current->string, "\n");
     printf("%-10s | %2d\n", current->string, current->count);
 }


例如,使用文本时:

    mary had a little lamb
    its fleece was white as snow
    and every where that mary went
    the lamb was sure to go


唯一印出来的词是羔羊,雪,走了,走了

最佳答案

首先检查单词是否已经在列表中。如果它在列表中,则没有必要再次添加它。 search函数应返回LIST*,可用于增加其值。

还简化链接列表,如下所示:

while(fgets(line, sizeof(line), fp))
{
    for (char *token = strtok(line, delim); token; token = strtok(NULL, delim))
    {
        int found = 0;
        for(LIST* n = head; n; n = n->next)
            if(strcmp(n->string, token) == 0)
            {
                n->count++;
                found = 1;
            }
        if(found) continue;

        LIST *node = malloc(sizeof(LIST));
        node->next = NULL;
        node->count = 1;
        node->string = strdup(token);
        if(head)
            node->next = head;
        head = node;
    }
}

for(LIST* n = head; n; n = n->next)
    printf("%s, %d\n", n->string, n->count);

关于c - 链接列表仅打印文本文件行的最后一个单词,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47742156/

10-11 22:59
查看更多