我当前的任务是编写一个函数,该函数具有一个FILE
指针和一个指向字符串的指针.该函数应分析该字符串在给定文件中出现的次数,并以整数形式返回值.它还需要注意区分大小写.在我当前的程序中,我将单词"Dog"作为要在文件中找到的字符串.但是,即使.txt文件中有三次狗这个词,它也一直给我0.这是我在这里的第一篇帖子,我查看了其他关于这个话题的帖子,但他们无法修复它.
这就是我所try 的:
#include <stdio.h>
#include <string.h>
int searchAndCount(FILE *fp, const char *searchWord) {
int count = 0;
char buffer[4096];
while ((fgets(buffer, sizeof(buffer), fp)) != NULL) {
buffer[strlen(buffer) - 1] = '\0';
if (strcmp(buffer, searchWord) == 0) {
count++;
}
}
return count;
}
int main() {
FILE *fp;
int searchedWord;
const char *c = "dog";
fp = fopen("test.txt", "r");
if (fp == NULL) {
perror("File couldn't open properly");
return 1;
}
searchedWord = searchAndCount(fp, c);
printf("The word 'dog' occurs %d-times in the file\n", searchedWord);
fclose(fp);
return 0;
}
我的test.txt如下所示:
dog dog dogoggo dog.
我明白了这一点:
The word 'dog' occurs 0-times in the file
编辑:
所以从 comments 来看,我似乎需要实现strtok()
个我将研究这个函数.
但使用:
int searchAndCount(FILE *fp, const char *searchWord) {
int count = 0;
char buffer[4096];
while ((fscanf(fp, "%4095s", buffer)) == 1) {
if (strcmp(buffer, searchWord) == 0) {
count++;
}
}
return count;
}
或多或少解决了问题,而"狗".不会因为点而被计算在内.
解决方案:
int searchAndCount(FILE *fp, const char *searchWord) {
int count = 0;
char buffer[4096];
for (;;) {
fscanf(fp, "%*[^a-zA-Z]");
if (fscanf(fp, "%4095[a-zA-Z]", buffer) != 1)
break;
if (strcmp(buffer, searchWord) == 0)
count++;
}
return count;
}