淡然者

strcmp函数的两种实现

strcmp函数的两种实现,gcc测试通过。

 

一种实现:

C代码  收藏代码
  1. #include<stdio.h>  
  2.   
  3. int strcmp(const char *str1,const char *str2)  
  4. {  
  5.     /* 注释以下的五行(while循环)可以简写为: 
  6.      * for(;(*str1==*str2)&&*str1!='\0';str1++,str2++); 
  7.      *  */  
  8.     while((*str1==*str2)&&*str1!='\0')  
  9.     {  
  10.         str1++;  
  11.         str2++;  
  12.     }  
  13.   
  14.     if(*str1=='\0'&&*str2=='\0') return 1;  
  15.     else return -1;  
  16. }  
  17.   
  18. int main()  
  19. {  
  20.     char *st1="abdefg";  
  21.     char *st2="abcdefg";  
  22.     printf("%d\n",strcmp(st1,st2));  
  23.   
  24.     char *st3="12345";  
  25.     char *st4="12345";  
  26.     printf("%d\n",strcmp(st3,st4));  
  27.   
  28.     return 0;  
  29. }  
 

另一种实现:

C代码  收藏代码
  1. #include<stdio.h>  
  2.   
  3. int strcmp(const char *str1,const char *str2)  
  4. {  
  5.     while(str1!=NULL&&str2!=NULL)  
  6.     {  
  7.         while(*str1++==*str2++)  
  8.         {  
  9.             if(*str1=='\0'&&*str2=='\0') return 1;  
  10.         }  
  11.           
  12.         return -1; //不等的情况  
  13.     }  
  14.   
  15.     return -2; //有指针为空的情况  
  16. }  
  17.   
  18. int main()  
  19. {  
  20.     char *st1="abdefg";  
  21.     char *st2="abcdefg";  
  22.     printf("%d\n",strcmp(st1,st2));  
  23.   
  24.     char *st3="12345";  
  25.     char *st4="12345";  
  26.     printf("%d\n",strcmp(st3,st4));  
  27.   
  28.     char *st5="xyz",*st6=NULL;  
  29.     printf("%d\n",strcmp(st5,st6));  
  30.   
  31.     return 0;  
  32. }  

posted on 2015-05-14 12:26  wesun  阅读(871)  评论(0编辑  收藏  举报