c++中string的compare函数怎么使用
在C++中,可以使用string的compare函数来比较两个string对象的大小。该函数的原型如下:
int compare(const string& str) const;
调用该函数时,如果当前string对象小于str,则返回负值;如果当前string对象大于str,则返回正值;如果两个string对象相等,则返回0。
例如:
#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;
}
运行结果为:
str1 is less than str2
版权声明
本文仅代表作者观点,不代表米安网络立场。
上一篇:python如何提取数组中的数据 下一篇:sql中空值和null的区别是什么
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。