c - 多词搜索

标签 c arrays string search

我想设计一个代码,让我可以多次返回关键字的位置。例如,下面的程序返回 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/

相关文章:

c - 如何使指针 == null 测试通过?

c - --help 输出的正确格式

arrays - 从数组设置对象数组中的属性

javascript - 循环数组数组并将值递增到新数组中

java - 使用随机 int 的 ArrayIndexOutOfBoundsException

c - 字符串中所有可能的字符组合

ruby - 生产数据的去识别

c - malloc 返回负值

c - 如果我在循环中创建线程,则前 2 个线程不会被执行

c++ - 将字符串写入 char,同时将参数传递给字符串