String Comparison
Part of the Fundamentals section of Coddy's C++ journey — lesson 22 of 74.
In C++, comparing strings can be done in multiple ways. Since std::string is a class, it has overloaded operators that make string comparison intuitive and straightforward.
The most common way to compare strings is using comparison operators (==, !=, <, >, <=, >=):
string str1 = "hello";
string str2 = "hello";
string str3 = "Hello";
bool result1 = (str1 == str2); // true
bool result2 = (str1 == str3); // false (case-sensitive)
bool result3 = (str1 != str3); // trueYou can also use the compare() method, which returns 0 if strings are equal, a negative integer if the first string is lexicographically smaller, and a positive integer if it's larger. Note that the exact value is implementation-defined — it is not necessarily -1 or 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)Cheat sheet
In C++, you can compare strings using comparison operators or the compare() method.
Using comparison operators:
string str1 = "hello";
string str2 = "hello";
string str3 = "Hello";
bool result1 = (str1 == str2); // true
bool result2 = (str1 == str3); // false (case-sensitive)
bool result3 = (str1 != str3); // trueUsing the compare() method:
Returns 0 if strings are equal, <0 if first string is lexicographically smaller, >0 if larger:
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)Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison3Variables Part 2
Type DeclarationNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementConditional OperatorRecap - If ElseNested If - Else