string 比较

来自 https://blog.csdn.net/qq_33210042/article/details/119390196

   

C++ string字符串的比较是否相等 可以使用compare 也可以使用"=="

   

1 使用比较运算符 == >

#include <iostream>

#include <string>

using namespace std;

int main()

{

string a = "hello";

string b = "hello";

// 使用比较运算符

if (a == b)

{

cout << "ab相等" << endl;

}

else

{

cout << "ab不相等" << endl;

}

 

};

   

原理:两个字符串自左向右逐个字符相比(ASCII值大小相比较)。

#include<iostream>

#include<cstring>

using namespace std;

int main(){

string s1 = "123457";

string s2 = "127";

if(s1 > s2)printf("s1\n");

else printf("s2\n");

return 0;

}

// outputs2

2 使用compare() 函数

compare 比较2个字符串,当2个字符串相等的时候返回 0

#include <iostream>

#include <string>

using namespace std;

int main()

{

string a = "hello";

string b = "hello";

// 使用compare函数

if (a.compare(b) == 0)

{

cout << "ab相等" << endl;

}

else

{

cout << "ab不相等" << endl;

}

};

   

posted @   atomxing  阅读(106)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示