strcmp和memcmp两个字符串比较函数

在C语言中经常遇到比较两个字符串大小的问题,这里我列出两个常用的比较函数以及它们的具体用法和两者之间的区别。

strcmp函数:
函数原型:int strcmp(const char * s2,const char * s2);

功能:比较字符串s1和字符串s2的大小。

返回值:
s1大于s2,返回值大于零
s1等于s2,返回值等于零
s1小于s2,返回值小于零

特点:两个字符串之间是逐个按照它们的ASIIC大小来比较的,一旦发现其中一个大于或小于另一个时,比较结束,返回一个值,不然就一直比较到’\0’为止。
实例:

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

int main()
{
    int i = 0;
    char *s1 = "Hello bit!";
    char *s2 = "Hello bit!";

    i = strcmp(s1, s2);  
    if (i > 0)
    {
        printf("s1 is greater than s2\n");//s1大于s2
    }
    else if (0 == i)//变量比较时把变量放右边,这样可以防止出错
    {
        printf("s1 and s2 are identical\n");//s1等于s2
    }
    else
    {
        printf("s1 is less than s2\n");//s1小于s2
    }
    system("pause");
    return 0;
}

memcmp函数:
函数原型:
int memcmp(const void *buf1, const void *buf2, unsigned int count);

功能:比较内存区域buf1和buf2的前count个字节。

返回值:
s1大于s2,返回值大于零
s1等于s2,返回值等于零
s1小于s2,返回值小于零

特点:memcmp函数也是按ASICC码逐个比较,在strcmp的基础上多加了个功能,他能比较字符串中前count字节的大小。如果count == strlen(s1),那就是比较字符串中全部字符。
实例:

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

int main()
{
    char *s1 = "Hello,bit!";
    char *s2 = "Hello,bat!";
    int i = 0;
    i = memcmp(s1, s2, strlen(s1));   
    if (i > 0)
    {
        printf("s1 is greater than s2\n");/*s1大于s2*/
    }
    else if (0  == i)
    {
        printf("s1 and s2 are identical\n");/*s1等于s2*/
    }
    else
    {
        printf("s1 is less than s2\n");/*s1大于s2*/
    }
    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值