c++之手寫strcmp

int strcmp(const char* str1, const char*str2){
assert(str1 != NULL&&str2 != NULL);
while (*str1&&*str1 == *str2){
str1++;
str2++;
}指針

if (*(unsigned char*)str1 < *(unsigned char*)str2){
return -1;
}
else if (*(unsigned char*)str1 > *(unsigned char*)str2){
return 1;
}
else{
return 0;
}字符串

}

異常

注意:
1.參數是 const
2.異常輸入處理 assert(str1 != NULL&&str2 != NULL);
3.字符之間大小比較時必定要先將char*型指針先轉換爲unsigned char*
由於有符號字符值的範圍是-128~127,無符號字符值的範圍是0~255,而字符串的ASCII沒有負值。
例如 *str1的值爲1,*str2的值爲255。
原本*str1<*str2,可是有符號數中255是-1.

while

相關文章
相關標籤/搜索