c-查找每个字符在字符串链接列表中出现的次数



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

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

#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

问题是if(current->string == search)将指针(char*(与char进行比较。如果当前->字符串是可以使用if(*current->string == search)的单个字符。如果字符串包含多个字符,您必须告诉我字符串的CCD_;aa";正在搜索"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;
}

相关内容

  • 没有找到相关文章

最新更新