C++如何比较两个字符串或string是否相等strcmp()和compare()
作者:TechArtisan6
这篇文章主要介绍了C++如何比较两个字符串或string是否相等strcmp()和compare()问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
如果要比较的对象是char字符串
则利用函数
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;
}
运行结果


如果要比较的对象是两个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;
}


总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
