2020年7月14日 周二 天气阴 【不悲叹过去,不荒废现在,不惧怕未来】
今天在刷Leetcode的时候,遇到比较两个string是否相等的问题,在这里总结一下在C++里如果比较两个字符串是否相等(包含C风格字符串和string对象)。
一、C风格字符串
C风格字符串的比较使用的是strcmp()函数,原型如下:
int strcmp(const char* s1,const char* s2)
当s1<s2时,返回为负数;
当s1==s2时,返回0;
当s1>s2时,返回正数。
比较的规则为:
两个字符串自左向右逐个字符相比(按ASCII值大小相比较),直到出现不同的字符或遇’\0’为止。
例如:“a”>“A”, “A”<“B”, “study”>“student”
二、string对象
string对象的比较可以使用compare()函数,原型如下
int compare (const basic_string& s) const;
int compare (const Ch* p) const;
int compare (size_type pos, size_type n, const basic_string& s) const;
int compare (size_type pos, size_type n, const basic_string& s,size_type pos2, size_type n2) const;
int compare (size_type pos, size_type n, const Ch* p, size_type = npos) const;
返回值和strcmp()函数是一样的,小于返回负数,等于返回0,大于返回正数。
注意事项
除此之外,单个字符和string对象的比较还可以直接使用 “==”,相等的话返回值为1,否则为0。
但是,在比较两个C风格字符串时千万不能用 “==”,因为使用这个符号比较的是两个C风格字符串的首地址是否相等!
参考文献
https://blog.csdn.net/snowcatvia/article/details/97623072
https://blog.csdn.net/Allenlzcoder/article/details/78254693