C++中关系操作符(==)和std::string::compare()的区别

C++中关系操作符(==)和std::string::compare()的区别

关系操作符(==) 和 std::string::compare() 对比

  1. 返回值:关系操作符返回布尔值,而compare()返回无符号整数。
  2. 形参:关系操作符只需要两个字符串进行比较,一个是被比较的,一个是引用的,而compare()可以接受不同的参数来执行相应的任务。
  3. 比较方法:关系操作符根据当前字符特征按字典顺序比较字符,而compare()可以为每个字符串处理多个参数,以便您可以根据索引和长度指定子字符串。
  4. 操作:我们可以使用compare()直接对string对象的一部分进行比较,否则使用关系操作符将会是一个相当长的过程。
    例如:*将str1的第3位的3个字符与str2的第4位的3个字符进行比较。
* str1 = "GeeksforGeeks"
* str2 = "HelloWorld!"

使用compare()

// CPP code to perform comparison using compare()
#include <iostream>
using namespace std;

void usingCompare(string str1, string str2)
{
    // Direct Comparison
    if (str1.compare(2, 3, str2, 3, 3) == 0)
        cout << "Both are same";
    else
        cout << "Not equal";
}

// Main function
int main()
{
    string s1("GeeksforGeeks");
    string s2("HelloWorld !");
    usingCompare(s1, s2);

    return 0;
}

输出:

Not equal

使用关系操作符(==)

// CPP code for comparison using relational operator
#include <iostream>
using namespace std;

void relational_operation(string s1, string s2)
{
    int i, j;

    // Lexicographic comparison
    for (i = 2, j = 3; i <= 5 && j <= 6; i++, j++) {
        if (s1[i] != s2[j])
            break;
    }
    if (i == 6 && j == 7)
        cout << "Equal";
    else
        cout << "Not equal";
}

// Main function
int main()
{
    string s1("GeeksforGeeks");
    string s2("HelloWorld !");
    relational_operation(s1, s2);

    return 0;
}

输出:

Not equal

我们可以清楚地观察到在使用关系操作符时需要进行的额外处理。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程