模拟实现strncmp


模拟实现strncmp

注意strcmp只比较len个字符是否相等,这里给出了两种方法:
ps:我在调试过程中遇到了前置、后置++问题,结合前置、后置++的特性,通过理清判断和自增的顺序来决定使用哪一种++,最好的办法就是多调试走几遍代码,理清每一步的顺序和结果


程序代码如下:



#define _CRT_SECURE_NO_WARNINGS

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

//减法运算判断
int MyStrncmp1(const char *src, const char *dest, size_t len)
{
	assert(NULL != dest && NULL != src);

	int ret = 0;
	//这里使用后置--,因为ret是在src、dest向后自增之前进行减法运算判断的
	while (len-- && !(ret = *(unsigned char *)src - *(unsigned char *)dest) && *dest)
	{
		src++;
		dest++;
	}
	if (ret < 0)
	{
		ret = -1;
	}
	else if (ret > 0)
	{
		ret = 1;
	}
	return ret;
}

//比较运算判断
int MyStrncmp2(const char* dest, const char* src, size_t len)
{
	assert(NULL != dest && NULL != src);

	//这里使用前置--,因为ret是在src、dest向后自增之前进行减法运算判断的
	while (--len && (*dest) && (*src == *dest))
	{
		*dest++;
		*src++;
	}

	if (*(unsigned char*)dest > *(unsigned char*)src)
		return 1;
	else if (*(unsigned char*)dest < *(unsigned char*)src)
		return -1;
	else
		return 0;
}

int main()
{
	char str1[8] = "hehao";
	char str2[6] = "hello";
	printf("%d\n", MyStrncmp1(str1, str2,2));//前两个字符相等 1
	printf("%d\n", MyStrncmp1(str1, str2, 3));//前三个字符不相等 -1
	printf("%d\n", MyStrncmp1("he", "hello",3));//dest长度小于len
	printf("%d\n\n", MyStrncmp1("hello", "he",3));//src长度小于len

	printf("%d\n", MyStrncmp2(str1, str2, 2));
	printf("%d\n", MyStrncmp2(str1, str2, 3));
	printf("%d\n", MyStrncmp2("he", "hello", 3));
	printf("%d\n\n", MyStrncmp2("hello", "he", 3));
	system("pause");
	return 0;
}


程序运行结果如下:


在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值