在写程序的过程中,经常会遇到要比较两个字符串是否相等的情况。如果要比较的对象是char字符串,则利用
int strcmp(const char s1,const char* s2)
当s1 < s2时,返回为负数;
当s1 == s2时,返回值= 0;
当s1 > s2时,返回正数。
即:两个字符串自左向右逐个字符相比(按ASCII值大小相比较),直到出现不同的字符或遇’\0’为止。如:
“A”<“B” “a”>“A” “computer”>“compare”
特别注意:strcmp(const char *s1,const char * s2)这里面只能比较字符串,即可用于比较两个字符串常量,或比较数组和字符串常量,不能比较数字等其他形式的参数。
ANSI标准规定,返回值为正数,负数,0 。而确切数值是依赖不同的C实现的。
如果要比较的对象是两个string,则利用函数compare()。若要比较string s1和s2则写为:s1.compare(s2),若返回值为0,则两者相等。
注意:在比较两个字符串时不能利用符号 “ == ”,“ == ”符号比较的是两个字符串的地址是否相等。
若是比较两个字符,则可以用""直接进行比较~
但在比较两个string对象时是可以利用“”的,相等的话,则表达式的返回值为1,不等为0。
#include <iostream>
#include <ctime>
#include <string>
#include <stdlib.h>
#include <string.h>
using std::string;
using namespace std;
int main(int argc, char *argv[]){int a = strcmp("Assa","assa");cout<<a<<endl;return 0;
}
写完用g++编译,出现error: ‘strcmp’ was not declared in this scope
上网查找发现必须再加上#include <string.h>才能正确编译执行,即同时存在
#include <string.h>
#include
using std::string;
也就是说strcmp不在C++标准库中,需要单独包含strcmp所在的头文件