String comparison
- C++ course
- Beginner
- Lesson 91/116
- 5 min
Learn string comparison operators.
String comparison operators
You test whether two strings are equal with ==, and their order with <, >, <=, >=. Comparison is done in dictionary order.
string a = "apple";
string b = "banana";
if (a == b) { /* equal */ }
if (a < b) { /* a comes first */ }The operators are case-sensitive: "Apple" and "apple" are not equal. Equality checks the string contents character by character; if lengths differ the result is immediately false.
The compare method
The .compare() method of the string class gives more detail. It returns 0 if equal, a negative value if the calling string is smaller, and a positive value if larger.
string a = "apple";
string b = "apple";
int c = a.compare(b); // c = 0This method is handy when sorting algorithms need a comparator. For simple equality == is more readable; but when a three-way comparison is needed, .compare() is preferred.
Practice Compare two strings and print
Define string a = "cherry"; and string b = "cherry";. Test equality with if (a == b); if equal, print cout << "same" << endl;. Otherwise print cout << "different" << endl;.
Starter code
#include <iostream>
#include <string>
using namespace std;
int main() {
string a = "cherry";
string b = "cherry";
// compare with ==, print "same" if equal, otherwise "different"
return 0;
}Sample solution
#include <iostream>
#include <string>
using namespace std;
int main() {
string a = "cherry";
string b = "cherry";
if (a == b) {
cout << "same" << endl;
} else {
cout << "different" << endl;
}
return 0;
}Expected output
same
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the string class's compare() return for two equal strings?
- 1
- -1
- true
- 0 Correct answer
Explanation: For equal strings, compare() returns 0.
2 Match each expression with its result
| Term | Meaning |
|---|---|
"a" == "a" |
equal |
"a" < "b" |
comes first |
"b" < "a" |
comes after |
3 Fill in the blank: equality check
string a = "apple";
string b = "banana";
if (a ____ b) {
cout << "same";
}
string a = "apple";
string b = "banana";
if (a == b) {
cout << "same";
}
Explanation: == tests whether the contents of two strings are equal.