注意转化为unsigned char:
strcmp.h
1 #ifndef STRCMP_H 2 #define STRCMP_H 3 4 /*************************************************** 5 功能:比较字符串s1和s2。 6 一般形式:strcmp(s1,s2) 7 返回值: 8 当s1<s2时,返回值<0 9 当s1=s2时,返回值=0 10 当s1>s2时,返回值>0 11 ****************************************************/ 12 13 int cat_strcmp(const char *src, const char *dst) { 14 int ret = 0; 15 16 while (!(ret = (*(unsigned char *)src - *(unsigned char *)dst)) && *dst) 17 ++src, ++dst; 18 19 if (ret < 0) 20 ret = -1; 21 else if (ret > 0) 22 ret = 1; 23 24 return ret; 25 } 26 27 #endif
main:
1 #include "strcmp.h" 2 3 4 void test_strcmp(); 5 6 int main() { 7 test_strcmp(); 8 9 return 0; 10 } 11 12 void test_strcmp() { 13 char *s1 = "compare", *s2 = "compase"; 14 printf("%d\n", cat_strcmp(s1, s2)); 15 16 char *s3 = "compare", *s4 = "compar"; 17 printf("%d\n", cat_strcmp(s3, s4)); 18 19 char *s5 = "compar", *s6 = "compare"; 20 printf("%d\n", cat_strcmp(s5, s6)); 21 22 printf("%d\n", cat_strcmp(s3, s6)); 23 }
/**
拓展:
unsigned char和char:
http://blog.sina.com.cn/s/blog_5c6f793801019oij.html
http://blog.csdn.net/world7th/article/details/1543575
*/
弦上故人来,纸底乱飞红。