模拟字符串实现库函数(strncpy ,strncat ,strncmp )

1.模拟实现strncpy 

//1.模拟实现strncpy  
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
char * mystrncpy(char * dest, const char * sour, int num)
{
	char *p = dest;
	char *q = sour;
    assert(dest != NULL);
	assert(sour != NULL);
	while (num!=0)
	{
		if (*q!="\0")
		{
			*p = *q;
			p++;
			q++;
		}
		else
		{
			break;
		}
		num--;
	}
	return dest;
}
int main()
{
	char arr1[] = "hello future";
	char arr2[20] = { 0 };
	printf("%s\n", mystrncpy(arr2, arr1, 10));
	system("pause");
	return 0;
}


2.模拟实现strncat 

//2.模拟实现strncat
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
char * mystrncat(char * dest, const char * sour, int num)
{
	char *ret = dest;
	assert(dest != NULL);
	assert(sour != NULL);
	while (*dest)
	{
		dest++;
	}
	while (num && (*dest++ = *sour++) != 0)
	{
		num--;
	}
	return ret;
}
int main()
{
	char arr1[30] = "To be ";
	char arr2[20] = "or not to be!!!";
	printf("%s\n", mystrncat(arr1, arr2, 13));
	system("pause");
	return 0;
}


3.模拟实现strncmp 

//3.模拟实现strncmp
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int mystrncmp(const char *s1, const char *s2, size_t  len)
{
	//判断str1与str2指针是否为NULL
	assert(s1 != NULL && s2 != NULL);

	while (len--)
	{
		if (*s1 == 0 || *s1 != *s2)
		{
			return *s1 - *s2;
		}
		s1++;
		s2++;
	}
	return 0;
}

int main()
{
	char arr1[] = "abcdeg";
	char arr2[] = "abcdfg";
	int tem = mystrncmp(arr1, arr2,5);//1: arr1大 返回1    2: arr2大 返回-1  3: 相等  返回0
	printf("%d\n", tem);
	if (tem==1)
	{
		printf("arr1>arr2");
	}
	else if (tem==-1)
	{
		printf("arr1<arr2");
	}
	else if (tem == 0)
	{
		printf("arr1=arr2");
	}
	system("pause");
	return 0;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值