我有个问题:
假设有两个 std::string
s,我想比较它们,有使用 compare()
函数的选项 string
类但我也注意到可以使用简单的 < > !=
运算符(即使我不包括 <string>
库,这两种情况都是可能的)。如果可以使用简单的运算符进行比较,有人可以解释为什么存在 compare()
函数吗?
顺便说一句,我使用 Code::Blocks 13.12 这是我的代码示例:
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::getline;
int main()
{
string temp1, temp2;
cout << "Enter first word: ";
getline (cin,temp1);
cout << "Enter second word: ";
getline (cin,temp2);
cout << "First word: " << temp1 << endl << "Second word: " << temp2 << endl;
if (temp1 > temp2)
{
cout << "One" << endl;
}
if (temp1.compare(temp2) < 0)
{
cout << "Two" << endl;
}
return 0;
}
原文由 Medvednic 发布,翻译遵循 CC BY-SA 4.0 许可协议
.compare()
返回一个整数,它是两个字符串之间差异的度量。0
表示两个字符串比较相等。operator==
简单地返回一个布尔值,指示字符串是否相等。如果您不需要额外的细节,您也可以使用
==
。