5

例如我有:

char buff[1000];

我想搜索字符串“hassasin”是否在该字符数组中。这是我尝试过的。

char word[8] = "hassasin";
char Buffer[1000]=sdfhksfhkasd/./.fjka(hassasin)hdkjfakjsdfhkksjdfhkjh....etc 
int k=0;
int t=0; 
int len=0; 
int sor=0; 
for (k=0; k<1000; k++){ 
    for (t=0; t<8; t++){ 
        if (Buffer[k]==word[t]) len++; 
        if (len==8) "it founds 0.9.1" 
    } 
}
4

2 回答 2

26

是的,您可以只使用strstr

 #include <stdlib.h>
 #include <string.h>

 char buff[1000];
 char *s;

 s = strstr(buff, "hassasin");      // search for string "hassasin" in buff
 if (s != NULL)                     // if successful then s now points at "hassasin"
 {
     printf("Found string at index = %d\n", s - buff);
 }                                  // index of "hassasin" in buff can be found by pointer subtraction
 else
 {
     printf("String not found\n");  // `strstr` returns NULL if search string not found
 }
于 2012-11-19T09:26:01.247 回答
2

如果 chararray 包含 stringend 或不以 \0 结尾,您可以使用这些代码,因为 strstr 会阻止这些代码:

#include <stdio.h>
int main()
{
    char c_to_search[5] = "asdf";

    char text[68] = "hello my name is \0 there is some other string behind it \n\0 asdf";

    int pos_search = 0;
    int pos_text = 0;
    int len_search = 4;
    int len_text = 67;
    for (pos_text = 0; pos_text < len_text - len_search;++pos_text)
    {
        if(text[pos_text] == c_to_search[pos_search])
        {
            ++pos_search;
            if(pos_search == len_search)
            {
                // match
                printf("match from %d to %d\n",pos_text-len_search,pos_text);
                return;
            }
        }
        else
        {
           pos_text -=pos_search;
           pos_search = 0;
        }
    }
    // no match
    printf("no match\n");
   return 0;
}

http://ideone.com/2In3mr

于 2012-11-19T09:41:36.717 回答