在C++中,可以使用string的compare函数来比较两个string对象的大小。该函数的原型如下:
int compare(const string& str) const;
调用该函数时,如果当前string对象小于str,则返回负值;如果当前string对象大于str,则返回正值;如果两个string对象相等,则返回0。
例如:
#include#include 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; }
运行结果为:
str1 is less than str2