【C】库函数之 strcmp

目录

1. Compare two strings

2. 源代码

3. 输出结果


1. Compare two strings

#include <string.h>
int strcmp ( const char * str1, const char * str2 );

Compares the C string str1 to the C string str2.

This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached.

This function performs a binary comparison of the characters. For a function that takes into account locale-specific rules, see strcoll.

上述内容是 cplusplus 对 strcmp 函数的介绍,可以看出 strcmp 函数用来比较两个字符串的大小。

  • 若 str1 指向内容 > str2 指向内容 ,则返回一个正数;
  • 若 str1 指向内容 < str2 指向内容 ,则返回一个负数;
  • 若 str1 指向内容 == str2 指向内容 ,则返回 0。

如果需要 对字符串中指定个数的字符 比较大小,则可以参考 strncmp函数实现

2. 源代码

int Strcmp(const char *s1, const char *s2) {
    assert((NULL != s1) && (NULL != s2));
   
    while (('\0' != *s1) && (*s1 == *s2)) {
        ++s1;
        ++s2;
    }
   
    return *s1 - *s2;
}  
   
void test() {
    char str1[] = "ab";
    char str2[] = "abc";
    int ret = Strcmp(str1, str2);
   
    if (ret > 0)
        printf("call Strcmp, str1: %s > str2: %s\n", str1, str2);
    else if (0 == ret)
        printf("call Strcmp, str1: %s == str2: %s\n", str1, str2);
    else
        printf("call Strcmp, str1: %s < str2: %s\n", str1, str2);
}  
   
int main(void) {  
    test();
   
    return 0;
}

3. 输出结果

call Strcmp, str1: ab < str2: abc

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值