頭文件: #include <cstring>
原型:int strcmp ( const char * s1, const char * s2 )
功能:比較兩個(gè)字符串的大小
思路:兩個(gè)字符串自左向右逐個(gè)字符相比(按ASCII值大小相比較),直到出現(xiàn)不同的字符或遇'/0'為止。
若s1 == s2,返回0;
若s1 > s2,返回正數(shù);
若s1 < s2,返回負(fù)數(shù);
實(shí)現(xiàn):
int strcmp(const char *s1, const char *s2){ assert( (NULL != s1) && (NULL != s2) ); while( *s1 == *s2){ if( *s1 == '/0') return 0; s1 ++; s2 ++; } return *s1 - *s2;}??不可用while ( *str1++ == *str2++ )來(lái)比較,當(dāng)不相等時(shí)仍會(huì)執(zhí)行一次 ++ ,導(dǎo)致 return 返回的比較值實(shí)際是下一個(gè)字符。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注