c++ 字符串比较函数

1. 使用 std::string 类的成员函数

可以使用其成员函数 `compare()` 来比较两个字符串

std::string::compare()


这个函数在多个重载版本中提供,可以用来比较整个字符串或字符串的子串。它返回:
(1)0 如果两个字符串相等
(2)负数 如果第一个字符串小于第二个字符串
(3)正数 如果第一个字符串大于第二个字符串

示例代码

#include <iostream>
#include <string>

int main() {
    std::string str1 = "Hello";
    std::string str2 = "World";
    std::string str3 = "Hello";

    std::cout << "Comparing str1 and str2: " << str1.compare(str2) << std::endl;
    std::cout << "Comparing str1 and str3: " << str1.compare(str3) << std::endl;

    return 0;
}

 strcmp()


这个函数位于 <cstring>(或 <string.h>)头文件中,用来比较两个C风格的字符串。返回值与 std::string::compare() 类似。

示例代码

#include <iostream>
#include <cstring>

int main() {
    const char* cstr1 = "Hello";
    const char* cstr2 = "World";
    const char* cstr3 = "Hello";

    std::cout << "Comparing cstr1 and cstr2: " << strcmp(cstr1, cstr2) << std::endl;
    std::cout << "Comparing cstr1 and cstr3: " << strcmp(cstr1, cstr3) << std::endl;

    return 0;
}

在C++中使用 std::string 的 compare() 函数时,不能直接使用 compare(a, b) 的形式。这是因为 compare() 是 std::string 类的成员函数,需要通过一个字符串对象来调用,比如 a.compare(b)。这里的 a 和 b 都应是 std::string 对象。

简单来说,compare() 需要这样使用:
1. 首先,你有两个 std::string 对象,比如 std::string a 和 std::string b。
2. 然后,你通过调用第一个字符串对象的 compare() 函数,将第二个字符串对象作为参数传入,即 a.compare(b)。

这个函数会比较两个字符串,并根据比较结果返回整数。这个整数说明了第一个字符串相对于第二个字符串的字典顺序位置。

如果想要一种类似于直接调用 compare(a, b) 的简便方式,可以考虑使用全局函数 std::lexicographical_compare(),但这通常用于比较范围(如数组或向量),或者直接使用重载的比较运算符,如 a == b、a < b 等,这些都是 std::string 类内置支持的。

  • 7
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值