2012-11-19 75 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' - 這是一個非常簡單的功能,在寫它的過程中你會學到很多東西。 –

相關問題