头文件: #include <cstring>
原型:int strcmp ( const char * s1, const char * s2 )
功能:比较两个字符串的大小
思路:两个字符串自左向右逐个字符相比(按ASCII值大小相比较),直到出现不同的字符或遇'\0'为止。
若s1 == s2,返回0;
若s1 > s2,返回正数;
若s1 < s2,返回负数;
实现:
int strcmp(const char *s1, const char *s2){
assert( (NULL != s1) && (NULL != s2) );
while( *s1 == *s2){
if( *s1 == '\0') //在循环中*s1 == *s2,若*s1 == '\0',则*s2也为'\0'
return 0;
s1 ++;//若未到字符串结尾,继续遍历直至找到*s1 != *s2时,退出循环
s2 ++;
}
return *s1 - *s2;
}
⚠️不可用while ( *str1++ == *str2++ )来比较,当不相等时仍会执行一次 ++ ,导致 return 返回的比较值实际是下一个字符。