C语言——字符串函数(strlen,strcpy,strcat,strcmp)模拟实现

1.strlen 函数模拟实现

strlen 函数介绍

声明

参数

str 是字符串的地址

返回值

返回‘\0’之前的字符串长度

模拟实现

首先获取到字符串的地址,

然后对地址解引用判断是否是‘\0’,

如果是,则返回count的值

如果不是,则count自增1。

size_t my_strlen(const char*str)
{
	
	//计数
	size_t count = 0;
	while (*str)//当*str‘\0’时,循环结束
	{
		str++;
		count++;
	}
	return count;
}
int main()
{
	char str[] = { "abcdef" };
	size_t ret = my_strlen(str);
	printf("%d", ret);
	return 0;
}

2.strcpy的模拟实现

strcpy的介绍

声明

参数

destination指向要复制内容的目标数组的指针。

source 要复制的 C 字符串。

返回值

返回destination

模拟实现

char* my_strcpy(char* destination, char* source)
{
	//先将destination存起来,方便后面返回destination
	char* tmp = destination;
	//复制
	while (*source)
	{
		*destination = *source;
		destination++;
		source++;
	}
	//如果source的长度小于destination,将destination其余元素转换成‘\0’
	if (*destination != '\0')
	{
		*destination = '\0';
	}
}
int main()
{
	char destination[50] = { "abcde" };
	char source[] = { "fgh" };
	my_strcpy(destination, source);
	printf("%s", destination);
	return 0;
}

3.strcat的模拟实现

声明

参数

destination指向目标数组的指针,该数组应包含 C 字符串,并且足够大以包含连接的结果字符串

source要附加的 C 字符串。

返回值

返回destination

模拟实现

char* my_strcat(char* destination, char* source)
{
	//找到destination的'\0'
	while (*destination)
	{
		destination++;
	}
	//追加
	while (*source)//遇到‘\0’终止循环
	{
		*destination = *source;
		destination++;
		source++;
	}
}
int main()
{
	char destination[50] = { "abcde" };//为了能存下要追加的字符串,开辟50个空间大小
	char source[] = { "fghij" };
	my_strcat(destination, source);
	printf("%s", destination);
	return 0;
}

4.strcmp的模拟实现

声明

参数

str1被比较的字符串

str2被比较的字符串

返回值

模拟实现

int my_strcmp(char* str1, char* str2)
{
	
	while (*str1 && *str2)
	{
		if (*str1 - *str2 > 0)
			return 1;
		else
			return -1;
	}
	
	if (*str1 != 0)
		return 1;
	else
		return -1;
}
int main()
{
	char str1[] = { "abcde" };
	char str2[] = { "abcdf" };
	int ret=my_strcmp(str1, str2);
	printf("%d", ret);
	return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

earthwormer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值