C语言实现strncmp

代码

#include 
#include 
#include 

int mystrncmp(const char * str1,const char  * str2,size_t n)
{
        assert( (str1 != NULL) && (str2 != NULL));
        while((*str1 == *str2) && (*str1 != '\0') && (*str2 != '\0') && (n--))
        {
                str1++;
                str2++;
        }
        if( (*str1 == *str2) || (n == 0))
        {
                return 0;
        }
        else if( *str1 > *str2)
        {
                return 1;
        }
        else
        {
                return -1;
        }
}

int main()
{

        char *str1 = "hello1";
        char *str2 = "hello2";
        printf("%d\n",mystrncmp(str1,str2,5));
        printf("%d\n",mystrncmp(str1,str2,6));
        printf("%d\n",mystrncmp(str1,str2,7));

        printf("%d\n",mystrncmp(str1,str1,5));
        printf("%d\n",mystrncmp(str1,str1,6));
        printf("%d\n",mystrncmp(str1,str1,7));

        printf("%d\n",mystrncmp(str2,str1,5));
        printf("%d\n",mystrncmp(str2,str1,6));
        printf("%d\n",mystrncmp(str2,str1,7));
        return 0;

}

执行

0
-1
-1
0
0
0
0
1
1

 

你可能感兴趣的:(C)