【问题标题】:Multiple word search多词搜索
【发布时间】:2014-12-16 07:07:37
【问题描述】:

我希望提供一个代码,让我可以多次返回关键字的位置。例如,下面的程序返回 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);
}

【问题讨论】:

    标签: c arrays string search


    【解决方案1】:

    由于 strstr 返回指向您的搜索字符串第一次出现的指针,您可以将返回值用作 strstr 的新起点,只要您没有得到空指针。

    或多或少:

    ret = strstr(haystack, needle);
    while(ret!=NULL)
    {
    printf("The substring is: %t\n", ret-haystack);
    ret++;
    ret = strstr(ret , needle); 
    }
    

    【讨论】:

    • +1,但null 通常拼写为NULL,并且一些编译器(正确地)抱怨使用%d 进行size_t 指针减法。
    • 是的,你是对的,更好的解决方案是使用 %zp 作为 printf。
    • 其实两个指针的差值产生的类型是有符号类型ptrdiff_t(而不是像size_t这样的无符号类型),正确的格式长度限定符是t .
    【解决方案2】:

    试试这个……

      int a=0;
      ret = strstr(haystack+a,needle);
      printf("The substring is: %d\n", (a=ret-haystack));
        while(strlen(haystack+a+strlen(needle))>strlen(needle))
        {
           ret = strstr(haystack+a+strlen(needle),needle);
           printf("The substring is: %d\n", (a=ret-haystack));
        }
    

    【讨论】:

      【解决方案3】:

      Tobias 是在正确的轨道上,但请记住 strstr 将匹配字符串开头的指针,因此您将陷入无限循环。

      int main() {
          char haystack[] = "TutorialsPointandPoint";
          char needle[] = "Point";
      
          char *search = haystack;
      
          while(search != NULL)
          {
              search = strstr(search, needle);
      
              if(search)
              {
                  search++;
                  printf("The substring is: %zu\n", search - haystack);
              }
          }
      
          return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 2021-05-01
        • 2015-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多