赞
踩
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
写程序的时候我们经常会遇到要比较两个字符串是否相等,下面将介绍几种比较方法
写法:int strcmp(const char s1,const char*s2)
当s1 < s2时,返回为负数;
当s1 == s2时,返回值= 0;
当s1 > s2时,返回为正数。
代码示例
- #include<iostream>
- #include<string.h>
- using namespace std;
- int main()
- {
- char s1[] = "aaa", s2[] = "aaa";
- cout << "s1==s2(相等为1,不等为0):" << (s1 == s2) << endl;
-
- if (!strcmp(s1, s2))
- cout << "s1和s2相等" << endl;
- else
- cout << "s1和s2不相等" << endl;
- }
a其实是一个指向字符串的指针,用“==”比较的时候相当于比较的是地址
注:头文件#include<string.h>
strcmp(const char s1,const char s2) 这里面只能比较字符串,即可用于比较两个字符串常量,或比较数组和字符串常量,不能比较数字等其他形式的参数。
写法:s1.compare(s2)
当s1 < s2时,返回为负数;
当s1 == s2时,返回值= 0;
当s1 > s2时,返回为正数。
代码示例
- #include<iostream>
- #include<string>
- using namespace std;
- int main()
- {
- string s1 = "aaa", s2 = "aaa";
- cout << "s1==s2(相等为1,不等为0):" << (s1 == s2) << endl;
-
- if (!s1.compare(s2))
- cout << "s1和s2相等" << endl;
- else
- cout << "s1和s2不相等" << endl;
- }
注:头文件#include<string>
比较两个string对象时,也可以用“==”,相等为1,不等为0。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。