ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 간과할 수 있는 문자열 비교 실수
    개발/C·C++ 2019. 10. 1. 12:51

    문자열이 담긴 변수를 비교할 때 등호(==)를 써도 될까? 안 될 것은 없다. 비교하고 싶은 것이 주소인지, 실제 값인지에 따라 쓰임이 다를 뿐이다. 자바에서도 마찬가지인데, C++에서 문자열을 비교할 때 등호를 사용하게 되면 주소를 비교한다. 선언과 동시에 리터럴로 초기화한 문자열이라면 주소가 같기 때문에 등호로 검사하면 당연히 같다는 결과가 나온다. 디버깅으로 주소를 비교해보면 a, b는 주소가 같다. 같은 리터럴로 초기화했으니까.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    #include <cstdio>
    #include <string.h>
    int main()
    {
        const char* a = "I am so sorry";    
        const char* b = "I am so sorry";    
        if (a == b)
            printf("같다\n"); // 같다고 출력된다
        else
            printf("다르다\n");    
        return 0;
    }
    http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter

     

    다음의 경우를 살펴보자. 같은 리터럴로 초기화하지 않았는데, DB에서 카운트 값을 얻어오는 상황을 예로 들어볼 수 있다. 문자열의 시작 주소를 포인터에 담는 것과 배열에 쓰는 것은 다르다. 때문에 == 연산자로 비교하면 같은 문자열을 출력하는 변수라도 엄연히 다르다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    #include <cstdio>
    #include <string.h>
    int main()
    {
        const char* a = "I am so sorry";
        char b[20];
        sprintf_s(b, "%s""I am so sorry");
        if (a == b)
            printf("같다\n");
        else
            printf("다르다\n"); // 다르다고 출력된다
        return 0;
    }
    http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter

     

    검사하고자 하는 문자열 변수의 주소가 아니라 실제 들어있는 값을 검사해야 올바른 문자열 비교가 된다. <string.h>에 있는 strcmp를 사용해 문자열 비교를 해주자. strcmp(const char* lhs, const char* rhs)에서 두 문자열이 같으면 0을 반환하며, 사전 기준으로 lhs이 빠르면 -1, lhs가 rhs보다 뒤에 있으면 1을 반환한다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    #include <cstdio>
    #include <string.h>
    int main()
    {
        const char* a = "I am so sorry";
        char b[20];
        sprintf_s(b, "%s""I am so sorry");
        if (strcmp(a, b) == 0)
            printf("같다\n"); // 같다고 출력된다
        else
            printf("다르다\n");
        return 0;
    }
    http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter

    댓글

Designed by Tistory.