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

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

字符运算符 vs std::string::compare()

  1. 返回值: 关系运算符返回布尔值,而 compare() 返回 unsigned integer。
  2. 参数: 关系运算符仅需要两个字符串进行比较,一个用于比较,另一个作为参考;而 compare() 可以接受不同的参数执行相应的任务。
  3. 比较方法: 关系运算符按字典顺序比较字符,而 compare() 可以为每个字符串处理多个参数,因此您可以通过索引和长度指定子字符串。
  4. 操作: 我们可以直接使用 compare() 在字符串的一部分中执行比较,而使用关系运算符则需要进行一些较长的处理。 示例: * 比较从 str1 的第三个位置开始的 3 个字符和从 str2 的第四个位置开始的 3 个字符。
  • str1 = “GeeksforGeeks”
  • str2 = “HelloWorld!”

使用 compare():

// 使用 compare() 进行比较的 CPP 代码
#include <iostream>
using namespace std;
 
void usingCompare(string str1, string str2)
{
    // 直接比较
    if (str1.compare(2, 3, str2, 3, 3) == 0)
        cout << "两个字符串相同";
    else
        cout << "不相等";
}
 
// 主函数
int main()
{
    string s1("GeeksforGeeks");
    string s2("HelloWorld !");
    usingCompare(s1, s2);
 
    return 0;
}  

输出:

不相等

使用关系运算符:

// 使用关系运算符进行比较的 CPP 代码
#include <iostream>
using namespace std;
 
void relational_operation(string s1, string s2)
{
    int i, j;
 
    // 字典比较
    for (i = 2, j = 3; i <= 5 && j <= 6; i++, j++) {
        if (s1[i] != s2[j])
            break;
    }
    if (i == 6 && j == 7)
        cout << "相等";
    else
        cout << "不相等";
}
 
// 主函数
int main()
{
    string s1("GeeksforGeeks");
    string s2("HelloWorld !");
    relational_operation(s1, s2);
 
    return 0;
}  

输出:

不相等

我们可以清楚地看到使用关系运算符时需要进行的额外处理。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程