C++ 比较两个字符串或string是否相等[ strcmp() 和 compare() ]

在这里插入图片描述

注:转载请标明原文出处链接:https://xiongyiming.blog.csdn.net/article/details/101097219


1 如果要比较的对象是 char 字符串,则利用函数 strcmp(const char s1,const char s2)

strcmp(const char s1,const char s2)
当 str1 < str2 时,返回为负数(-1);
当 str1 == str2 时,返回值= 0;
当 str1 > str2 时,返回正数(1)。

:strcmp(const char s1,const char s2) 这里面只能比较字符串,即可用于比较两个字符串常量,或比较数组和字符串常量,不能比较数字等其他形式的参数。


代码示例


#include<iostream>
#include<string>

using namespace std;

int main()
{

	char str1[10000];
	char str2[10000];

	cout << "两个字符串比较是否相同" << endl;
	cout << "请输入第一个字符串:" << endl;
	cin.get(str1, 10000).get();

	cout << "请输入第二个字符串:" << endl;
	cin.get(str2, 10000).get();
	

	if (strcmp(str1, str2) == 0)
	{
		cout << "您输入的两个字符串相同" << endl;
	}
	else
	{
		cout << "您输入的两个字符串不相同" << endl;
	}


	system("pause");
	return 0;
}

运行结果

在这里插入图片描述

在这里插入图片描述



2 如果要比较的对象是两个string,则利用函数 compare()
若要比较string s1和s2则写为:s1.compare(s2),若返回值为0,则两者相等。

当s1 < s2时,返回为负数(-1);
当s1 == s2时,返回值= 0;
当s1 > s2时,返回正数(1)。


代码示例


#include<iostream>
#include<string>

using namespace std;

int main()
{


	char str1[10000];
	char str2[10000];

	string s1;
	string s2;
	cout << "两个字符串比较是否相同" << endl;

	cout << "请输入第一个字符串:" << endl;
	cin.get(str1, 10000).get();

	cout << "请输入第二个字符串:" << endl;
	cin.get(str2, 10000).get();

	s1 = str1;
	s2 = str2;

	if ( (s1.compare(s2)) == 0 )
	{
		cout << "您输入的两个字符串相同" << endl;
	}
	else
	{
		cout << "您输入的两个字符串不相同" << endl;
	}


	system("pause");
	return 0;
}


在这里插入图片描述


在这里插入图片描述



参考资料

[1] https://blog.csdn.net/Allenlzcoder/article/details/78254693

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TechArtisan6

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值