我想设计一个代码,让我可以多次返回关键字的位置。例如,下面的程序返回 9,即数组中第一个 Point 出现的位置。但是,我希望搜索整个数组中的所有关键字,因为关键字可以在我负责搜索的数组中出现多次。基本上我希望能够根据字符串返回 9、17 等等。
我正在考虑加入某种循环,但我对 strstr 命令没有经验,无法确定。
#include <stdio.h>
#include <string.h>
int main()
{
char haystack[30] = "TutorialsPointandPoint";
char needle[10] = "Point";
char *ret;
ret = strstr(haystack, needle);
printf("The substring is: %d\n", ret-haystack);
return(0);
}
最佳答案
当 strstr 返回指向搜索字符串第一次出现的指针时,您可以使用返回值作为 strstr 的新起点,只要您没有得到空指针。
或多或少:
ret = strstr(haystack, needle);
while(ret!=NULL)
{
printf("The substring is: %t\n", ret-haystack);
ret++;
ret = strstr(ret , needle);
}
关于c - 多词搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26480245/