模拟实现C语言库函数strcmp

首先看一下MSDN中对它的定义,函数参数,返回值
strcmp
(定义)Compare strings.

(函数参数)int strcmp( const char *string1, const char *string2 );

(返回值)The return value for each of these functions indicates the lexicographic relation of string1 to string2.

接下来,我们看一下代码实现

#include<stdio.h>
#include<windows.h>
int my_strcamp(const char* p,const char* q)
{
    assert(p && q);
    int ret = 0;
    while (*p == *q)
    {
        if (*p == '\0')
            return 0;
        p++;
        q++;
    }
    if (*p > *q)    //C语言标准规定,第一个字符串比第二个大,只需返回一个大于零的数,比第二个小,只需返回一个比零小的数字。
        return 1;   //所以这里的if,else判断也可以替换为下面的代码
    else            //   return *p - *q;
        return -1;  //
}
int main()
{
    char* arr1 = "abcde";
    char* arr2 = "abc";
    int ret = my_strcamp(arr1, arr2); 
    printf("%d",ret);
    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/aixintianshideshouhu/article/details/81216604