我有一个问题:
假设有两个 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;
}
最佳答案
.compare()
返回一个整数,用于衡量两个字符串之间的差异。
- 返回值
0
表示两个字符串比较相等。 - 正值表示比较的字符串更长,或者第一个不匹配的字符更大。
- 负值表示比较的字符串较短,或者第一个不匹配的字符较短。
operator==
只返回一个 bool 值,指示字符串是否相等。
如果你不需要额外的细节,你也可以使用 ==
。
关于c++ - 使用 std::string::compare 比较字符串,C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24957965/