C++ String Compare: Complete Guide
In C++, you can use the compare function of string to compare the sizes of two string objects. The prototype of this function is as follows:
int compare(const string& str) const;
When the function is invoked, it returns a negative value if the current string object is smaller than str, a positive value if the current string object is larger than str, and returns 0 if the two string objects are equal.
For example,
#include <iostream>
#include <string>
int main() {
std::string str1 = "hello";
std::string str2 = "world";
if (str1.compare(str2) < 0) {
std::cout << "str1 is less than str2" << std::endl;
} else if (str1.compare(str2) > 0) {
std::cout << "str1 is greater than str2" << std::endl;
} else {
std::cout << "str1 is equal to str2" << std::endl;
}
return 0;
}
The result of the operation is:
str1 is less than str2