[c语言]strcmp函数的使用和模拟实现

时间:2024-11-08 11:15:41

1.strcmp函数的使用

int strcmp ( const char * str1, const char * str2 );
  • 如果 str1 小于 str2,返回一个负值。
  • 如果 str1 等于 str2,返回 0。
  • 如果 str1 大于 str2,返回一个正值。

实例:

#include <stdio.h>
#include <string.h>

int main() {
    char str1[] = "abc";
    char str2[] = "acb";
    char str3[] = "abc";

    int result1 = strcmp(str1, str2);
    int result2 = strcmp(str1, str3);

    printf("strcmp(str1, str2) = %d\n", result1); // 输出负值,因为"abc" < "acb"
    printf("strcmp(str1, str3) = %d\n", result2); // 输出0,因为"abc" == "abc"

    return 0;
}

运行结果:

 

2.strcmp模拟实现

#include <stdio.h>
#include <string.h>
#include <assert.h>
int my_strcmp(const char* src, const char* dest)
{
    int ret = 0;
    assert(src != NULL);
    assert(dest != NULL);
    while (!(ret = *(unsigned char*)src - *(unsigned char*)dest) && *dest)
        ++src, ++dest;
    if (ret < 0)
        ret = -1;
    else if (ret > 0)
        ret = 1;
    return(ret);
}
int main() {
    char str1[] = "abc";
    char str2[] = "acb";
    char str3[] = "abc";

    int result1 = my_strcmp(str1, str2);
    int result2 = my_strcmp(str1, str3);

    printf("strcmp(str1, str2) = %d\n", result1); // 输出负值,因为"abc" < "acb"
    printf("strcmp(str1, str3) = %d\n", result2); // 输出0,因为"abc" == "abc"

    return 0;
}