String Compare
beginner
c++11
strings
The std::string class from the Standard Library has the equals operator (==) and the not equals operator (!=) which can be used to compare two strings for equality.
#include <iostream> #include <string> const char* as_string(bool b) { return b ? "true" : "false"; } int main() { std::string s{"Hello cppbyexample.com"}; std::cout << as_string(s == "cppbyexample.com") << "\n"; std::cout << as_string(s != "cppbyexample.com") << "\n"; std::string s2{"Hello cppbyexample.com"}; std::cout << as_string(s == s2) << "\n"; std::cout << as_string(s != s2) << "\n"; }
false true true false
std::string also supports less than (<) and greater than (>) operators.
This is useful for comparing and sorting strings alphabetically.
#include <iostream> #include <string> #include <vector> #include <algorithm> // sort const char* as_string(bool b) { return b ? "true" : "false"; } int main() { std::vector<std::string> v{ "Genesis", "Boston", "ABBA", "Cream"}; std::cout << as_string(v[0] < v[1]) << "\n"; std::cout << as_string(v[0] > v[1]) << "\n"; std::sort(v.begin(), v.end()); for (const auto& s : v) { std::cout << s << "\n"; } }
false true ABBA Boston Cream Genesis
std::string also has a compare() method which returns int.
The return value is negative if the string on the left of the expression comes before the one on the right, positive the string on the left comes after, and 0 if they are equal.
#include <iostream> #include <string> int main() { std::string abba{"ABBA"}; std::string boston{"Boston"}; std::string genesis{"Genesis"}; std::cout << abba.compare(boston) << "\n"; std::cout << genesis.compare(boston) << "\n"; std::cout << boston.compare(boston) << "\n"; }
-1 5 0