2013-10-12 2 views
1

문자열 내에 하위 문자열을 찾는 할당 코드를 작성해야합니다. 여기 하위 문자열 찾기

내 코드입니다, 내가 코멘트를 추가 :이 방법을 테스트 할 때

// the target is the substring that we want to find in the source string 
// m is the length of the target, and n is the length of the source 
int contains(char target[], int m, char source[], int n) { 
int flag = 0; // the source originally does not contain the target 
int i; 

    // go through each character of the source string 
for(i = 0; i < n; i++) { 
    int targetIndex = 0; 
    int j; 

      // check if the preceding characters of the source string are a substring 
      // that matches the target string 
    for(j = i; j < n && targetIndex < m; j++) { 
     if(target[targetIndex] == source[j]) { 
      flag = 1; 
      targetIndex += 1; 
     } 
     else { 
      flag = 0; // a letter does not match 
      break; 
     } 
    } 
} 

return flag; 

}

그래서, 난 항상 0 반환받을를 내가 이유를 이해할 수 없다.
int i = contains("potatoes", 8, "toes", 4);을 입력하면 0이됩니다.
일부 인쇄 문을 입력하여 어떤 문자와 일치하는지 확인하려고 시도했으며 첫 문자가 "t" 인 것 같습니다.

+1

이것은 기본적으로'strstr()'이므로, 구현 예를 살펴 보시기 바랍니다. 지. glibc에있는 하나. –

+0

이 코드를 수정 하시겠습니까? 또는 더 나은 방법을 원하십니까? –

답변

1

일치하는 항목이 있으면 for 외부를 부러 뜨려야합니다.

코드가 작동하는 방식으로 일치하는 항목을 찾은 다음 바깥 쪽 루프를 다시 실행하고 "잊어 버리십시오".

1

는 다음과 같이하십시오 :

for(i = 0; i < n; i++) { 
    int targetIndex = 0; 
    int j; 

      // check if the preceding characters of the source string are a substring 
      // that matches the target string 
    for(j = i; j < n && targetIndex < m; j++) { 
     if(target[targetIndex] == source[j]) { 
      flag = 1; 
      targetIndex += 1; 
     } 
     else { 
      flag = 0; // a letter does not match 
      break; 
     } 
    } 
    if(flag == 1) 
    { 
    break; 
    } 
} 

당신 대신 당신을 위해 일을 더 쉽게 만들 것입니다 C의 strstr 기능을 시도 할 수 있습니다.

예 :

char *x= "Find the substring in this string"; 
char *y= "substring"; 
if(strstr(x, y) != NULL) { 
    return true; 
} 
+0

바깥 쪽'break;'는 무조건적입니다 –

+0

@GrijeshChauhan : - 가리키는 것에 대해 Grijesh에게 감사드립니다. 내 대답이 업데이트되었습니다. 그러나 OP가 채택해야하는 두 번째 옵션이 더 좋다고 생각합니다! –

+0

이제는 좋았지 만, 당신은 inner를위한 루프에서'else {..}'를 사용할 필요가 없습니다. 바깥 쪽 break 루프 전에'flag = 0'을 설정하면됩니다. 또한'return i;'대신'break'를 사용하지 마십시오. 바깥 쪽. –

0

설명 주석과 코드에 약간의 수정.

// the target is the substring that we want to find in the source string 
// m is the length of the target, and n is the length of the source 
int contains(char target[], int m, char source[], int n) { 
int flag = 0; // the source originally does not contain the target 
int i; 

    // go through each character of the source string 
for(i = 0; i < n; i++) { 
    int targetIndex = 0; 
    int j; 

      // check if the preceding characters of the source string are a substring 
      // that matches the target string 
    for(j = i; j < n && targetIndex < m; j++) { 
     if(target[targetIndex] == source[j]) { 
      targetIndex += 1; 
      if(targetIndex == m) { // the 'target' has been fully found 
       flag = 1; 
       break; 
      } 
     } 
     else 
     { 
      break; 
     } 
    } 
    if(flag == 1) // 'target' is already found, no need to search further 
    { 
     break; 
    } 
} 

return flag; 
} 

부분 문자열이 완전히 발견되면 내부 루프와 외부 루프를 모두 차단하십시오.

EDITED : int i = contains("potatoes", 8, "toes", 4); 대신 기능 설명에 따라 int i = contains("toes", 4, "potatoes", 8);이어야합니다.

관련 문제