C++比较字符串的字典序

strcmp(s1, s2)

在 C 语言中,我们可以使用 strcmp() 函数比较 char* 类型字符串的字典序。

  • 当字符串 s1 的字典序小于字符串 s2 的字典序时,返回值 < 0。
  • 当字符串 s2 的字典序大于字符串 s1 的字典序时,返回值 > 0。
  • 当字符串 s1 的字典序等于字符串 s2 的字典序时,返回值 = 0。
#include <iostream>
using namespace std;

int main() {
    char s1[2] = "a";
    char s2[2] = "b";
    cout << strcmp(s1, s2) << endl; //-1
    cout << strcmp(s2, s1) << endl; //1
    cout << strcmp(s1, s1) << endl; //0
    return 0;
}

s1.compare(s2)

在 C++ 中,我们可以使用compare() 函数比较 char* 类型和 string 类型字符串的字典序。compare() 函数和 strcmp() 函数的返回值相同。

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s1 = "a";
    string s2 = "b";
    cout << s1.compare(s2) << endl; //-1
    cout << s2.compare(s1) << endl; //1
    cout << s1.compare(s1) << endl; //0
    return 0;
}

<

此外,在 C++ 中,我们还可以使用比较运算符比较 char* 类型和 string 类型字符串的字典序,注意使用比较运算符比较 char* 类型字符串时,需要将 char* 类型强制转换为 string 类型,否则比较的则是字符串的起始地址。

#include <iostream>
using namespace std;

int main() {
    char s1[2] = "a";
    char s2[2] = "b";
    cout << (s1 < s2) << endl;  //0
    cout << &s1 << endl;        //00BDFE74
    cout << &s2 << endl;        //00BDFE68
    cout << (string(s1) < string(s2)) << endl;  //1
    cout << (string(s2) < string(s1)) << endl;  //0
    cout << (string(s1) == string(s1)) << endl; //1
    return 0;
}
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值