string 之 strcmp函数

更多干货请移步我的公众号「aCloudDeveloper」,专注技术干货分享,期待与你相遇。

Author: bakari  Date: 2012/8/9

继上篇。。。。。

下面是我写的代码与源码作的一些比较,均已严格测试通过,分别以“string 之”系列述之。

下面包括strcmp , stricmp , strncmp函数

1 //strcmp
2 int Mystrcmp(const char *str1, const char *str2);
3 int Mystricmp(const char *str1, const char *str2);
4 int Mystrncmp(const char *str1, const char *str2, size_t nCount);
 1 /*******************************************************
 2  *  strcmp , stricmp and strncmp
 3  *  stricmp and strncmp need to improve!
 4  *  stricmp ignore case , but strcmp not!
 5  *******************************************************/
 6 int Mystrcmp(const char *str1, const char *str2){
 7     assert(NULL != str1 && NULL != str2);
 8     while(*str1 && *str2 && (*str1 == *str2)){
 9             str1 ++;
10             str2 ++;
11     }
12    
13    /* This is source code,Great ! */
14    /* int ret;
15     while(1){
16         if((ret = (*str1++ - *str2)) != 0 || !*str2 ++)
17             break;
18     }
19     return ret;
20     */
21     return (*str1 - *str2);
22 }
23 int Mystricmp(const char *str1, const char *str2){
24     assert(NULL != str1 && NULL != str2);
25     while(*str1 && *str2){
26         if((*str1 == *str2) || (*str1 + 32 == *str2) || (*str1 - 32 == *str2)){
27             str1++;
28             str2++;
29             continue;
30         }
31     }
32     return *str1 - *str2;
33 }
34 int Mystrncmp(const char *str1, const char *str2, size_t nCount){
35     assert(NULL != str1 && NULL != str2 && nCount <= \
36            ((strlen(str1) < strlen(str2))? strlen(str1): strlen(str2)));
37     while((--nCount) && (*str1 == *str2) ){
38             str1 ++;
39             str2 ++;
40     }
41     return *str1 - *str2;
42 }

有不同解法的欢迎交流!

posted @ 2012-08-09 19:49  bakari  阅读(893)  评论(0编辑  收藏  举报