2012-11-19 72 views
3

比如我有:如何在C中的char数组中搜索字符串?

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" 
    } 
} 
+2

你应该尝试编写自己的代码,然后询问如果你没”成功。 – Maroun

+0

我试过但我找不到真正的答案 – hassasin

+6

我不知道我遇到过多少次“关闭......这个问题不太可能对未来的访问者有所帮助”,答案非常有帮助。 – Dermot

回答

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

+0

好的,但我认为这个代码是找到字符串,即使有必要的字母之间还有其他元素。在我的搜索中,我想找到确切的词,没有其他字母之间。我该怎么做? – hassasin

+0

此代码搜索完全相同的单词。 如果你想搜索它与你周围的空间可以搜索“asdf” – phschoen

+0

我没有得到它每次它找到一个匹配的信件,它正在做++ pos_search。它不一定是成功的,当它达到4时就说我找到了。 – hassasin

19

是的,你可以只使用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 
} 
+0

谢谢。有没有办法手动做到这一点?没有使用任何方法? – hassasin

+3

当然是的 - 如果这是一个家庭作业练习,那么你可以自己实现'strstr' - 这是一个非常简单的功能,在写它的过程中你会学到很多东西。 –

相关问题