문자열 비교
Coddy C++ 여정의 기초 섹션에 포함된 레슨 — 74개 중 22번째.
C++에서 문자열 비교는 여러 가지 방법으로 수행될 수 있습니다. std::string은 클래스이므로, 문자열 비교를 직관적이고 간단하게 만들어주는 오버로드된 연산자들을 가지고 있습니다.
문자열을 비교하는 가장 일반적인 방법은 비교 연산자(==, !=, <, >, <=, >=)를 사용하는 것입니다:
string str1 = "hello";
string str2 = "hello";
string str3 = "Hello";
bool result1 = (str1 == str2); // true
bool result2 = (str1 == str3); // false (대소문자 구분)
bool result3 = (str1 != str3); // true또한 compare() 메서드를 사용할 수도 있습니다. 이 메서드는 문자열이 같으면 0을 반환하고, 첫 번째 문자열이 사전순으로 더 작으면 음수 정수를, 더 크면 양수 정수를 반환합니다. 정확한 값은 구현에 따라 정의되며, 반드시 -1이나 1인 것은 아니라는 점에 유의하세요:
string str1 = "a";
string str2 = "b";
string str3 = "c";
cout << str2.compare(str1) << endl;
// Positive (b comes after a)
cout << str2.compare(str3) << endl;
// Negative (b comes before c)
cout << str2.compare(str2) << endl;
// 0 (equal strings)치트 시트
C++에서는 비교 연산자 또는 compare() 메서드를 사용하여 문자열을 비교할 수 있습니다.
비교 연산자 사용:
string str1 = "hello";
string str2 = "hello";
string str3 = "Hello";
bool result1 = (str1 == str2); // true
bool result2 = (str1 == str3); // false (대소문자 구분)
bool result3 = (str1 != str3); // truecompare() 메서드 사용:
문자열이 같으면 0을 반환하고, 첫 번째 문자열이 사전순으로 더 작으면 <0, 더 크면 >0을 반환합니다:
string str1 = "a";
string str2 = "b";
string str3 = "c";
cout << str2.compare(str1) << endl; // 양수 (b는 a 뒤에 옴)
cout << str2.compare(str3) << endl; // 음수 (b는 c 앞에 옴)
cout << str2.compare(str2) << endl; // 0 (동일한 문자열)직접 해보기
이 레슨에는 코드 챌린지가 없습니다.
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.