【问题标题】:Find how many times each character appears in a linked list of strings [duplicate]找出每个字符在字符串链表中出现的次数[重复]
【发布时间】:2021-06-24 00:14:30
【问题描述】:

我必须找出每个字符在字符串链表中重复的次数。字符串被存储并从文件中读取。我必须以两种方式打印结果:字母顺序和增长顺序。

我试图编写一个函数来计算给定字符重复的次数,但它崩溃了。

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


struct list {
    char *string;
    struct list *next;
};

typedef struct list LIST;

int count(struct list* head, char search) // funct to calculate how many 
                                          //times 1 string appears
{
    struct list* current = head;
    int count=0;
    while (current!=NULL)
    {
        if(current->string == search)
            count++;
    }
    return count;
}

int main(void) {
    FILE *fp;
    char line[128];
    LIST *current, *head;

    head = current = NULL;
    fp = fopen("test.txt", "r");

    while(fgets(line, sizeof(line), fp)){
        LIST *node = malloc(sizeof(LIST));
        node->string = strdup(line);
        node->next =NULL;

        if(head == NULL){
            current = head = node;
        } else {
            current = current->next = node;
        }
    }
    fclose(fp);
    //test print
    for(current = head; current ; current=current->next){
        printf("%s", current->string);
    }

    count(head, "a");

    return 0;
}

test.txt 文件包含:

Astazi nu este maine

【问题讨论】:

  • 我在 int count 函数中的 count++ 之后添加了一行 current = current-&gt;next; 但是当打印出来时,它打印我 0,虽然它应该是 2
  • 您的示例依赖于您未与我们共享的 test.txt。我建议您简化示例并对测试数据进行硬编码以演示问题。
  • @AllanWind 刚刚编辑了描述,我已经将 test.txt 中的数据放入其中
  • this C reference。使用GCC 编译您的C 代码,调用为gcc -Wall -Wextra -g,改进您的代码以不收到警告,然后使用GDB 调试器了解您的可执行文件的行为。
  • 这里的问题是你的代码从编译器发出了几个警告,但你没有在问题中提到它。您应该google这些警告消息并阅读相关的 Stack Overflow 问题甚至在发布您自己的问题之前。

标签: c file linked-list


【解决方案1】:

问题在于if(current-&gt;string == search) 将指针 (char *) 与 char 进行比较。如果 current->string 是单个字符,您可以使用 if(*current-&gt;string == search)。如果字符串包含多个字符,您必须告诉我字符串“aa”的count() 是什么,搜索“a”。另一个主要问题是count() 中的while 循环不会遍历链表,因此会导致无限循环。

int count(struct list *head, char search) {
    int count = 0;
    for(struct list* current = head; current; current = current->next) {
        for(int i = 0; current->string[i]; i++)
            if(current->string[i] == search) count++;
    }
    return count;
}

【讨论】:

  • 这个问题实际上是说问题出在应该计算字符串中单个字符出现次数的函数中,而您根本没有解决。
  • 很公平,我还在写我的答案。
  • @AllanWind 感谢您的帮助。虽然,当我尝试打印它时,它仍然给我 0,也许我使用了错误的 prinf:printf("\n%d", count(head, "a"));
  • count 需要一个字符,因此您需要将其称为count(head, 'a') 例如:printf("%d\n", count(head, 'a')); 当 test.txt 包含两行带有“a”s 时返回 2。
  • @Vlad,我明白了,你现在输入。查看更新的答案。
猜你喜欢
  • 1970-01-01
  • 2012-05-10
  • 2014-08-31
  • 1970-01-01
  • 2021-01-11
  • 2018-01-30
  • 1970-01-01
  • 2021-11-29
  • 1970-01-01
相关资源
最近更新 更多