문자열 비교 함수

2024. 10. 31. 15:16프로그래밍 언어로

1. ==, !=, <, >, <=, >= 연산자

C++의 std::string 클래스는 기본적으로 비교 연산자를 오버로딩하여 문자열 비교를 지원합니다.

#include <iostream>
#include <string>

int main() {
    std::string str1 = "apple";
    std::string str2 = "banana";

    if (str1 == str2) {
        std::cout << "두 문자열이 같습니다.\n";
    } else if (str1 < str2) {
        std::cout << "str1이 사전순으로 더 앞에 있습니다.\n";
    } else {
        std::cout << "str1이 사전순으로 더 뒤에 있습니다.\n";
    }
    return 0;
}

2. compare() 멤버 함수

std::string의 compare 함수는 두 문자열을 사전순으로 비교하고, 결과로 정수값을 반환합니다.

  • 반환값이 0이면 두 문자열이 같습니다.
  • 반환값이 0보다 작으면 호출한 문자열이 인수보다 사전순으로 앞에 있습니다.
  • 반환값이 0보다 크면 호출한 문자열이 인수보다 뒤에 있습니다.
#include <iostream>
#include <string>

int main() {
    std::string str1 = "apple";
    std::string str2 = "banana";

    int result = str1.compare(str2);

    if (result == 0) {
        std::cout << "두 문자열이 같습니다.\n";
    } else if (result < 0) {
        std::cout << "str1이 str2보다 사전순으로 앞에 있습니다.\n";
    } else {
        std::cout << "str1이 str2보다 사전순으로 뒤에 있습니다.\n";
    }
    return 0;
}

3. C 스타일 문자열 비교 (strcmp)

#include <iostream>
#include <cstring>

int main() {
    const char* str1 = "apple";
    const char* str2 = "banana";

    int result = strcmp(str1, str2);

    if (result == 0) {
        std::cout << "두 문자열이 같습니다.\n";
    } else if (result < 0) {
        std::cout << "str1이 str2보다 사전순으로 앞에 있습니다.\n";
    } else {
        std::cout << "str1이 str2보다 사전순으로 뒤에 있습니다.\n";
    }
    return 0;
}

 

C++에서도 C 스타일의 문자열을 비교할 때 strcmp를 사용할 수 있습니다. strcmp는 <cstring> 헤더에 있으며, 두 const char* 문자열을 비교합니다.