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

标签 c++ string comparison

我有一个问题:

假设有两个 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/

相关文章:

c++ - 映射键排序

c++ - 解压缩二进制文件时错误的 EOF

c++ - 使用 char* 存储正确的文件路径

Python 字符串替换行为不同

c# - 有没有办法用 C# 中的给定比较函数在功能上比较两个已知大小相等的列表?

r - 绘制多重比较?

android - Cocos2dx 安卓构建错误: "arm-linux-androideabi-g++: No such file or directory"

java - Java 的错误答案

python - TypeError : list indices must be integers or slices,不是str字典python

c - 将结构与零进行比较的首选方法