我想用 c 语言编写一个代码,用于使用 strstr() 函数搜索在 txt 文件中找到某个字符串的次数。
我已经用 strastr() 编写了测试代码,但遇到了问题。
例如我有这样的句子 " this is a text"
当我搜索"is"
时我得到结果 "is found 2 times"
因为它从“this”中取出“is”。我不想接is
来自this
我想要"is"作为唯一的词。我可以使用 strstr() 进行一些更改来搜索而不出现此“问题”
#include <stdio.h>
#include<string.h>
int main()
{
char*ptr;
char input[]=("this is a text");
char key[10];
int counter;
scanf("%s",key);
ptr=strstr(input,key);
while (ptr==NULL)
{
printf("not found\n");
break;
}
while(ptr!=NULL)
{
counter++;
ptr=strstr(ptr+1,key);
}
printf("%s found %d times\n",key,counter);
return 0;
}
最佳答案
我猜您想在 C 中执行某种形式的正则表达式。在您的示例中,您正在寻找 "\bis\b"
,而不是字符 “is”
(在这种情况下,您将得到正确的结果)。
您可以考虑使用某种形式的正则表达式库。这些链接有一些信息:
Regular expressions in C: examples?
http://www.lemoda.net/c/unix-regex/
或者您可以考虑具体实现您正在寻找的内容。类似的东西
while(ptr!=NULL)
{
if (ptr == &input[0]) {
if (isspace(*(ptr+strlen(key)) || *(ptr+strlen(key)=='\0') {
counter++;
}
} else {
if (isspace(*(ptr-1) && (isspace(*(ptr+strlen(key)) || *(ptr+strlen(key)=='\0')) {
counter++;
}
}
ptr=strstr(ptr+1,key);
}
注意:我知道这段代码远未得到优化,但我认为它是有效的并且非常不言自明。
关于c - 在 txt 中使用 strstr() 找到一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23818452/