模拟实现C库函数strncpy、strncat、strncmp

1.模拟实现strncpy

char *my_strncpy(char *dest, const char* str, int count)
{
	assert(dest != NULL);
	assert(str != NULL);
	char *ret = dest;
	while (count && (*dest++ = *str++))
	{
		count--;
	}
	if (count>0)
	{
		while (--count)
		{
			*dest++ = '\0';
		}
	}
	return ret;
}


int main()
{
	char arr[10];
	my_strncpy(arr, "hello", 3);
	printf("%s\n", arr);
	system("pause");
	return 0;
}

2.模拟实现strncat

char *my_strncat(char*dest, const char*str, int count)
{
	assert(dest != NULL);
	assert(str != NULL);
	char *ret = dest;
	while (*dest)
	{
		dest++;
	}
	while (count && (*dest++ = *str++))
	{
		count--;
	}
	if (count > 0)
	{
		while (--count)
		{
			*dest++ = '\0';
		}
	}
	return ret;
}
int main()
{
	char arr1[20]="hello ";
	char arr2[] = "world";
	my_strncat(arr1, arr2, 7);
	printf("%s\n", arr1);
	system("pause");
	return 0;
}

3.模拟实现strncmp

strcmp函数原型:int strncmp ( const char * str1, const char * str2, size_t n );

                            若str1与str2的前n个字符相同,则返回0;若s1大于s2,则返回大于0的值;若s1 若小于s2,则返回小于0的值

strncmp()首先将s1 第一个字符值减去s2 第一个字符值,若差值为0 则再继续比较下个字符,直到字符结束标志'\0',若差值不为0,则将差值返回。

int my_strncmp(const char*str1,const char*str2,int count)
{
	assert(str1 != NULL);
	assert(str2 != NULL);
	int ret;
	while (count&&*str1&&*str2)
	{
		if (*str1 == *str2)
		{
			ret = 0;
			str1++;
			str2++;
		}
		else if (*str1 > *str2)
		{
			ret = 1;
			break;
		}
		else if (*str1 < *str2)
		{
			ret = -1;
			break;
		}
		count--;
	}
	return ret;
}
int main()
{
	char arr1[] = "hekkk";
	char arr2[] = "hekkk";
	int ret=my_strncmp(arr1, arr2, 6);
	printf("%d\n", ret);
	system("pause");
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值