2012-11-19 2 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

당신은 자신의 코드를 작성하려고 한 다음 didn를 묻는한다 ' t 성공. – 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'을 직접 구현할 수 있습니다. 이것은 매우 간단한 함수이고, 여러분은 그것을 작성하는 과정에서 많은 것을 배울 것입니다. –

관련 문제