有限制库函数的模拟

  有限制库函数:(strncpy,strncmp,strncat);

   无限制库函数:(strcpy,strcmp,strcat);

 首先让小编给各位友友讲一下有限制库函数和无限制库函数的区别。

有限制库函数和无限制库函数的区别:有限制库函数可以控制字符串拷贝的字符(strncpy),   可以控制两字符串比较的长度(strncmp),也可以控制一个字符串连接到另一字符串的长度。而无限制库函数不能控制字符串拷贝字符的个数(strcpy),也不能控制两字符串比较的长(strcmp)更不能控制一个字符串连接到另一字符串的长度(strcat);

然后小编再来讲一下有限制库函数使用模版及要求和用法说明。

char*destination是目标空间的起始地址,const char*source是源字符串的起始地址。

strncpy(char* destination,const char*source,size_t num);

函数说明:1.拷贝num个字符从源字符串到目标空间。

  2.如果源字符串的长度小于num,则拷贝完源字符串后,在目标的后面追加0,直到num个。

strncmp(const char*str1,const char*str2,size_t num)

函数声明:比较str1和str2前num个字符,如果相等则继续比较,最多可以比较num个字母,如果提前发现不一样就提前结束,如果str1>str2则返回大于零的数,如果str1<str2则返回一个小于零的数,str1=str2则返回零。

strncat(char* destination,const char*source,size_t num);

函数声明:1.将source指向字符串的前num个字符追加到destination指向的字符串末尾,再追加一个'\0'字符。tination

 2.如果source指向的字符串的长度小于num的时候,只会将字符串中岛'\0'的内容追加到destination指向的字符串末尾。

模拟实现有限制库函数

模拟实现strncpy

#include<stdio.h>
#include<string.h>
#include<assert.h>
char* my_strncpy(char* p1,const char* p2, int lenth, int n)//lenth为字符串p2的长度
{
	assert(p1 != NULL && p2 != NULL);//断言,判断p1和p2均不为空字符
	char* ret = p1;//因为再将p2内容拷贝到p1的过程中,p1的地址会改变不再是p1的起始位置
	if(lenth>n)
	{
		for (int i = 0; i < n; i++)
		{
			*p1++ = *p2++;
		}
	}
	else
	{
		int i = 0;
		for (i = 0; i < lenth; i++)
		{
			*p1++ = *p2++;
		}
		for ( ; i < n; i++)
		{
			*p1++ = '/0';
		}
	}
	return ret;
}

模拟实现strncmp

#include<stdio.h>
#include<string.h>
#include<assert.h>
int my_strncmp(const char* p1,const char* p2,int n)
{
assert(p1!=NULL&&p2!=NULL);
while(n--&&*str1==*str2)
{
str1++;str2++;
}
return *str1-*str2;
}

模拟实现strncat

#include<stdio.h>
#include<string.h>
#include<assert.h>
void my_strncat(char* ch1, const char* ch2, int lenth, int n)//lenth为ch2的长度
{
	assert(ch1 != NULL && ch2 != NULL);//断言
	char* ret = ch1;//p1的地址会被改变,利用一个指针变量保留ch1的起始地址
	int lench1=strlen(ch1);
	ch1 += lench1;//直接将ch1的地址改为ch1的末尾即为'\0'的位置
	if(n<=lenth)
	{
		while (n--)
		{
			*ch1++ = *ch2++;
		}
		*ch1 = '\0';
	}
	else
	{
		while (n--)
		{
			*ch1++ = *ch2++;
		}
	}
	ch1 = ret;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值