【发布时间】:2015-05-23 03:51:17
【问题描述】:
我正在尝试逐行读出我的文本文件
FILE *infile;
char line[1000];
infile = fopen("file.txt","r");
while(fgets(line,1000,infile) != NULL)
{
//....
}
fclose(infile);
然后我需要找到一个特定的单词,例如“the”,并且需要查看它出现了多少次以及它还出现在了哪些行上。
我应该可以用这个数单词
int wordTimes = 0;
if((strcmp("the", currentWord) == 0))
{
printf("'%s' appears in line %d which is: \n%s\n\n", "the", line_num, line);
wordTimes++;
}
其中line 是字符串所在的文本行,line_num 是字符串所在的行号。
然后单词显示的次数使用此代码:
if(wordTimes > 0)
{
printf("'%s' appears %d times\n", "the", wordTimes);
}
else
{
printf("'%s' does not appear\n", "the");
}
问题是我不确定如何将行中的每个单词与“the”进行比较,并且仍然打印出它适用的行。
为此我必须使用非常基本的 C,这意味着我不能使用 strtok() 或 strstr()。我只能使用strlen() 和strcmp()。
【问题讨论】:
-
你能自己模拟
strstr()和/或strtok()吗?您允许使用哪些功能 -strcmp()似乎可以,但还有什么? -
你只需要多次调用它,每次从最后一场比赛之后开始,直到它没有找到任何东西。您还必须确保在找到任何内容之前和之后都有一个非 alpha 版本。
-
你修改代码:
char *here = line; while ((word = strstr(here, "the")) != NULL) { wordcount++; here = word + 1; }除了你还需要检查单词是否被非字母字符包围。 -
调用
strstr()后,word指向三个连续字母the的开头,可能被空格包围,也可能不被空格包围,或者为空。 -
@DarkN3ss - 您必须在循环中调用它并每次将
return value of strstr + strlen("the")作为输入传递,直到strstr返回 0。
标签: c find-occurrences