String-Comparison
String-Comparison
Comparison
Compare strings with == and !=
Comparing with ==
The == operator can be used with strings just like it is with numbers or
boolean values. Note that without the boolalpha flag, the system will return
1 if true and 0 if false. 1 represents string equality and 0 represents
inequality.
challenge
Comparing with !=
You can also test for string inequality with the != operator.
Lexicographical Order
In C++, strings can be compared lexicographically, meaning they can be
compared according to how they will appear in the dictionary. You can use
the compare() method to determine which of two strings comes first. A
return value of a negative integer means the first string comes first, a
return value of a positive integer means the second string comes first, and
a return value of 0 means the strings are equal and neither comes first.
if (string1.compare(string2) < 0) {
cout << "string1 comes first" << endl;
}
else if (string1.compare(string2) > 0) {
cout << "string2 comes first" << endl;
}
else {
cout << "the strings are equal" << endl;
}
challenge
if (string1.compare(string2) < 0) {
cout << "string1 comes first" << endl;
}
else if (string1.compare(string2) > 0) {
cout << "string2 comes first" << endl;
}
else {
cout << "the strings are equal" << endl;
}
challenge