my_strncmp的写法

strncmp 函数的分析

1 函数原型

     extern int strncmp(char *s1, char * s2, int n);  

2 函数用法

     #include  <string.h>

3 函数功能

     比较字符串s1和s2的前n个字符。  

4 函数说明:

     当s1  当s1=s2时,返回值=0
     当s1>s2时,返回值>0

5 函数源码


int my_strncmp ( char * s1, char * s2, size_t n) 
{
    if ( !n )//n为无符号整形变量;如果n为0,则返回0
    {
        return(0);
    }

    //在接下来的while函数中 

    //第一个循环条件:--n,如果比较到前n个字符则退出循环

    //第二个循环条件:*s1,如果s1指向的字符串末尾退出循环

    //第二个循环条件:*s1 == *s2,如果两字符比较不等则退出循环

    while (--n && *s1 && *s1 == *s2) 
    { 
        s1++;//S1指针自加1,指向下一个字符

        s2++;//S2指针自加1,指向下一个字符
    }
    return( *s1 - *s2 );//返回比较结果
}

你可能感兴趣的:(函数,my-strncmp,C-语言)