2013-10-31 2 views
1
// Compares the two arguments. If they are equal, 0 is returned. If they 
// are not equal, the difference of the first unequal pair of characters 
// is returned. 
int strcmp(const char* charPointerToArray1, const char* charPointerToArray2) { 
    int i = 0; 
    // we need to check if both arrays have reached their terminating character 
    // because consider the case where array1 = { '\0' } and array2 = { '1', '\0' } 
    while (charPointerToArray1[i] != '\0' || charPointerToArray2[i] != '\0') { 
     // while iterating through both char arrays, 
     // if 1 char difference is found, the 2 char arrays are not equal 
     if (charPointerToArray1[i] != charPointerToArray2[i]) { 
      int differenceOfFirstUnequalChars = charPointerToArray1[i] - charPointerToArray2[i]; 
      return differenceOfFirstUnequalChars; 
     } else { 
      i++; 
     } 
    } 
    return 0; // charPointerToArray1 == charPointerToArray2 
} 

그래서 Cpp에서 문자열 비교 방법을 작성 했으므로 잘못된 것이 무엇인지 알 수 없습니다.내 문자열 비교가 Cpp에서 작동하지 않습니다.

+2

'||'는 '&&'여야합니다. 그리고 나서 로직을 약간 다시 작성해야합니다. 그 라인 위의 주석에있는 당신의 예에서, 당신은 그'if' 조건으로 범위를 벗어날 것입니다. – Simple

+0

나는 그 상태를 진술한다고 말하려고했으나, 나는 단순함이 그것의 권리를 가진다는 것을 내기하고있다. – IllusiveBrian

+1

또한 두 문자열의 길이가 다른 경우? – Matt

답변

1

다른 사람들은 코드를 보여 주며 여기에 대한 나의 견해입니다. 첫 번째와 두 번째 문자를 0과 비교 한 다음 계속 비교할 필요가 없습니다. 두 문자 중 하나가 0이되면이 끝나면 완료되고 차이 을 반환 할 수 있습니다. while 테스트의 두 번째 부분은 항상 실행되므로 이므로 r을 초기화 할 필요가 없습니다. 두 부분이 모두 true 일 필요가 있습니다.


주목할만한 점은 : 나는 본능적으로 결과의 부호를 뒤집은 것을 봅니다. 문자열 A와 B를 비교할 때 "A가 보다 작 으면이 B"인지 알기를 원할 것입니다. 이는 부정적인 결과로 표시됩니다.

#include <stdio.h> 

int my_strcmp (const char* charPointerToArray1, const char* charPointerToArray2) 
{ 
    int i = 0, r; 
    while ((charPointerToArray1[i] || charPointerToArray2[i]) && 
     !(r = (charPointerToArray2[i] - charPointerToArray1[i]))) 
    { 
     i++; 
    } 
    return r; 
} 

int main (void) 
{ 
    printf("%d\n", my_strcmp("foobar", "")); 
    printf("%d\n", my_strcmp("foobar", "foobaz")); 
    printf("%d\n", my_strcmp("foobar", "foobar")); 
    return 0; 
} 
0

내가 알 수있는 한, 당신의 기능은 훌륭합니다. 특히 다음과 같은 경우에는 작동하지 않습니다.

#include <stdio.h> 

int my_strcmp(const char* charPointerToArray1, const char* charPointerToArray2) { 
    int i = 0; 
    // we need to check if both arrays have reached their terminating character 
    // because consider the case where array1 = { '\0' } and array2 = { '1', '\0' } 
    while (charPointerToArray1[i] != '\0' || charPointerToArray2[i] != '\0') { 
     // while iterating through both char arrays, 
     // if 1 char difference is found, the 2 char arrays are not equal 
     if (charPointerToArray1[i] != charPointerToArray2[i]) { 
      int differenceOfFirstUnequalChars = charPointerToArray1[i] - charPointerToArray2[i]; 
      return differenceOfFirstUnequalChars; 
     } else { 
      i++; 
     } 
    } 
    return 0; // charPointerToArray1 == charPointerToArray2 
} 


int main() { 
    printf("%d\n", my_strcmp("", "foobar")); 
} 

예상되는 음수를 인쇄합니다.

(. strcmp()라는 점점 더 혼란이 없도록 내가 기능을 개명 한 나는 당신이 역시 할 것을 권장합니다.)

0

이 작동 예입니다있는 한

// Compares the two arguments. If they are equal, 0 is returned. If they 
// are not equal, the difference of the first unequal pair of characters 
// is returned. 
int strcmp(const char* charPointerToArray1, const char* charPointerToArray2) { 
    int i = 0; 
    // we need to check if both arrays have reached their terminating character 
    // because consider the case where array1 = { '\0' } and array2 = { '1', '\0' } 
    while (charPointerToArray1[i] != '\0' && charPointerToArray2[i] != '\0') { 
     // while iterating through both char arrays, 
     // if 1 char difference is found, the 2 char arrays are not equal 
     if (charPointerToArray1[i] != charPointerToArray2[i]) { 
      int differenceOfFirstUnequalChars = charPointerToArray1[i] - charPointerToArray2[i]; 
      return differenceOfFirstUnequalChars; 
     } else { 
      i++; 
     } 
    } 
    // return 0; // not really, one of the array may be longer than the other 
    if (charPointerToArray1[i] == '\0' && charPointerToArray2[i] == '\0') 
     return 0; 
    else //... one of the array is longer 
} 
관련 문제