使用 std::string::compare, c 比较字符串

新手上路,请多包涵

我有个问题:

假设有两个 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 许可协议

阅读 2.7k
2 个回答

.compare() 返回一个整数,它是两个字符串之间差异的度量。

  • 返回值 0 表示两个字符串比较相等。
  • 正值表示比较的字符串更长,或者第一个不匹配的字符更大。
  • 负值表示比较的字符串更短,或者第一个不匹配的字符更短。

operator== 简单地返回一个布尔值,指示字符串是否相等。

如果您不需要额外的细节,您也可以使用 ==

原文由 Tom Fenech 发布,翻译遵循 CC BY-SA 3.0 许可协议

string cat = "cat";
string human = "human";

cout << cat.compare(human) << endl;

此代码将给出 -1 作为结果。这是由于比较字符串的第一个不匹配字符 ‘h’ 低于或按字母顺序出现在 ‘c’ 之后,即使比较字符串 ‘human’ 比 ‘cat’ 长。

我发现 cplusplus.com 中描述的返回值更准确,它们是:

0 :它们比较相等

:比较字符串中第一个不匹配的字符的值较低,或者所有比较字符都匹配但比较字符串较短。

大于 0 :比较字符串中第一个不匹配的字符的值更大,或者所有比较字符都匹配但比较字符串更长。

此外,IMO cppreference.com 的描述更简单,迄今为止最好地描述了我自己的经验。

如果 *this 出现在参数指定的字符序列之前,则为负值,按字典顺序

如果两个字符序列比较相等,则为零

如果 *this 出现在参数指定的字符序列之后,则为正值,按字典顺序

原文由 Idz 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏