C 查找每个字符在字符串链接列表中出现的次数
我必须找出每个字符在字符串链表中重复的次数。字符串被存储并从文件中读取。我必须以两种方式打印结果:字母顺序和增长顺序 我曾尝试编写一个函数,该函数将计算给定字符的重复次数,但它崩溃了C 查找每个字符在字符串链接列表中出现的次数,c,file,linked-list,C,File,Linked List,我必须找出每个字符在字符串链表中重复的次数。字符串被存储并从文件中读取。我必须以两种方式打印结果:字母顺序和增长顺序 我曾尝试编写一个函数,该函数将计算给定字符的重复次数,但它崩溃了 #include <stdio.h> #include <stdlib.h> #include <string.h> struct list { char *string; struct list *next; }; typedef struct list
#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;
}
问题在于
if(current->string==search)
将指针(char*)与字符进行比较。如果当前->字符串是单个字符,则可以使用If(*current->string==search)
。如果字符串包含多个字符,您必须告诉我搜索“a”时字符串“aa”的count()
是什么。另一个主要问题是,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;
}
我在
int count
函数中的count++后面添加了一行,即current=current->next代码>但是当打印出来时,它会打印出0,尽管它应该是2。您的示例依赖于一个test.txt,您没有与我们共享。我建议您简化您的示例,并对测试数据进行硬编码以演示问题。@AllanWind刚刚编辑了描述,我已将test.txt中的数据放在了itSee中。使用调用的asgcc-Wall-Wextra-g
编译您的C代码,改进代码以不获取警告,然后使用调试器了解可执行文件的行为。这里的问题是,您的代码会从编译器发出多个警告,但您在问题中没有提及。您应该在发布自己的问题之前搜索这些警告消息并阅读相关的堆栈溢出问题。问题实际上表明,问题出在一个函数中,该函数应该计算字符串中单个字符的出现次数,而您根本没有解决该问题。这很公平,我还在写我的答案。@AllanWind谢谢你的帮助。虽然,当我试图打印它时,它仍然给我0,可能我使用了错误的prinf:printf(“\n%d”,count(head,“a”)
count接受一个字符,因此您需要将其称为count(head,'a')
例如:printf(“%d\n”,count(head,'a'))代码>当test.txt包含两行带有“a”的s时返回2。我知道了,现在是您的输入。请参阅更新的答案。
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;
}