gpt4 book ai didi

c - 使用 fgets 和 strstr 在 C 中查找和计算字符串

转载 作者:行者123 更新时间:2023-11-30 14:59:51 27 4
gpt4 key购买 nike

我正在尝试完成一项作业。这个想法是获取一个字符串数组和一个文件流。我需要在文件中查找这些字符串,并计算这些字符串的出现次数。

我想我已经掌握了基本的循环。唯一的问题是,当我在行中找到一个字符串时,我想从 1 + 找到的字符串开始的位置开始再次搜索该字符串(如果出现多次)。

#define LINE_MAX_CHARS 1000

// n = number of strings to be found
// **strings = array of strings to look for in file
void count_occurrences (int n, FILE *file, char **strings) {
char str[LINE_MAX_CHARS]; // buffer
int count = 0;
while (fgets(str, LINE_MAX_CHARS, file) != NULL){ // for each line
for (int i = 0; i < n; i++){ // for each word in line
char *found;
found = (strstr(str, (*(strings + i)))); // search line
if (found != NULL){ // if word found in line
// here, I want str (the buffer) to have its 0-th element to be the element at (found + 1),
// and the 1-st element to be (found + 2) and so on...
i--; // to look for same word in the rest of the line
count = count + 1;
}
}
}
}

另一个问题是我无法测试我的代码。我刚刚得到一个测试程序,它运行并告诉我我的代码是否产生正确的输出。

我需要使用 fgets 和 strstr。

建议?

最佳答案

strstr(str, strings[i]) 返回指向字符串中某个位置的指针。您应该能够递增该指针 (str++) 并将其直接传递回循环中的 strstr(),每次递增计数,如果 则结束循环strstr() 返回 NULLstr 命中空字符。

它应该看起来像这样。我还没有测试过这个;但由于这是你的作业,如果它不能正常工作/编译,我将把它留给你来调试。这意味着我不会为您完成所有工作...

;-)

void count_occurrences (int n, FILE *file, char **strings) {
char str[LINE_MAX_CHARS];
int count = 0;

while (fgets(str, LINE_MAX_CHARS, file) != NULL){
for (int i = 0; i < n; i++){
char *pos = str;

while(((pos = strstr(pos, strings[i]) != NULL) && *pos != '\n') {
count++;
pos++;
}
}
}
}

关于c - 使用 fgets 和 strstr 在 C 中查找和计算字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42475272/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com