OR搜索的strstr?

时间:2015-10-25 09:47:55

标签: c

这可能是一个基本的东西,但我找不到一个紧凑的解决方案。 我在一个更大的字符串中搜索一个字符串。 由于它的硬件有时我会丢失输入数据,所以我想检查一个更大的文本中是否存在一个单词,所以:

strstr(wifiContent,"SEND OK  HTTP:  Connection:) 
如果这些字词出现在组合中,

将在wifiContent内搜索,但我希望他返回> 0,即使只有一个是出现在字符串中,

所以对于这个输入:

SEND OK BLA BLA BLA.. BLA BLA BLA.. HTTP: ...BLA BLA BLA... Connection...bla

我想为搜索结果获得真实(或索引> 0)。

如何使用strstr实现此目的?

编辑:

我试过这个没有成功:

 char * pch;
           char *scopy;
           strcpy(scopy,wifiContent);
            pch = strtok (scopy," ,.-");
            while (pch != NULL)
            {
             if( strstr(wifiContent,pch) )
              return 1;

              pch = strtok (NULL, " ,.-");
            }

            if( strstr(wifiContent,target) )
               return 1;

3 个答案:

答案 0 :(得分:2)

这是一个简单的程序来演示如何做到这一点 -

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void)
{
   char a[]="SEND OK BLA BLA BLA.. BLA BLA BLA.. HTTP: ...BLA BLA BLA... Connection...bla";  
   char s[]="SEND OK HTTP:  Connection";    //string with words you want to check
   char *ret ,*token;
   int index=0;                          // declare index
   token=strtok(s," ");                  // tokenize s 
   while(token!=NULL){                   // check return of strtok
       ret=strstr(a,token);              // search words 
       if(ret!=NULL)                     // check return of strstr
           index++;                      // increment index
       token=strtok(NULL," ");              
   }
   printf("%d",index);                   // print index
   return 0;
}

这将基本搜索原始字符串中的这四个单词,如果找到任何一个单词,则递增index。这样原始字符串保持不变。

@Primary

答案 1 :(得分:1)

我已经设法在评论中的伟大人物的帮助下做到了这一点:

                    char * pch;
                    pch = strtok (target," ");
                    while (pch != NULL)
                    {
                     if( strstr(wifiContent,pch) )
                      return 1;

                      pch = strtok (NULL, " ");
                    }

                    if( strstr(wifiContent,target) )
                       return 1;

答案 2 :(得分:1)

你可以写:

return strstr(wifiContent, "SEND")
  || strstr(wifiContent, "OK")
  || strstr(wifiContent, "HTTP:")
  || strstr(wifiContent, "Connection");