注:转载请标明原文出处链接: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