比较字符串,c ++

Med*_*nic 20 c++ string comparison

我有个问题:

假设有两个std::strings,我想比较它们,可以选择使用类的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;
}    
Run Code Online (Sandbox Code Playgroud)

Tom*_*ech 35

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

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

operator== 只返回一个布尔值,指示字符串是否相等.

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


小智 8

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

cout << cat.compare(human) << endl; 
Run Code Online (Sandbox Code Playgroud)

这段代码将给出-1。这是由于比较字符串'h'的第一个不匹配字符较低或以字母顺序出现在'c'之后,即使比较字符串'human'比'cat'长。

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

0:它们比较相等

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

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

此外,IMO cppreference.com的描述更简单,到目前为止,根据我的经验可以最好地描述。

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

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

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