用std::string::compare比较字符串大小
参考见
http://www.cplusplus.com/reference/string/string/compare/
三种常见的重载形式:
int compare (const string& str) const noexcept;
int compare (size_t pos, size_t len, const string& str) const;
int compare (size_t pos, size_t len, const string& str,
size_t subpos, size_t sublen) const;
#include <iostream>
#include <string>
int main ()
{
std::string str1 ("green apple");
std::string str2 ("red apple");
if (str1.compare(str2) != 0)
std::cout << str1 << " is not " << str2 << '\n';
if (str1.compare(6,5,"apple") == 0)//第一个参数表示str1中的位置:str1[6],第二个参数表示要比较的字符串的最大数量,即从指定位置开始后的比较数目
std::cout << "still, " << str1 << " is an apple\n";
if (str2.compare(str2.size()-5,5,"apple") == 0)//同上
std::cout << "and " << str2 << " is also an apple\n";
if (str1.compare(6,5,str2,4,5) == 0)//str1中的“apple”和str2中的“apple”比较
std::cout << "therefore, both are apples\n";
return 0;
}
output如下:
green apple is not red apple
still, green apple is an apple
and red apple is also an apple
therefore, both are apples
注意:比较的结果不一定为1,0,-1,可能出现+2、-2等情况,当为正数时表示str1大于str2,为零时相等,为负数时小于str2
本文介绍了如何使用C++标准库中的std::string::compare函数来比较两个字符串的大小,并通过示例代码展示了三种重载形式的具体应用。文章还解释了比较结果的含义及其可能的数值范围。
1万+

被折叠的 条评论
为什么被折叠?



