常见字符串函数实现

今天模拟实现了一些c语言中stirng.h头文件中的常见函数。

1.memmove与memcpy

作用:把一段内存的内容移动到另一段内存中和复制内存内容到另一端内存中。

void* myMemmove(void* dest, const void* src, size_t count)
{
	assert(dest && src);
	if (src > dest)
	{
		//向前拷贝 - 从前拷贝
		for (int i = 0; i < count; i++)
		{
			*((char*)dest + i) = *((char*)src + i);
		}
	}
	else
	{
		//向后拷贝 - 从后拷贝
		for (int i = count - 1; i >= 0; i--)
		{
			*((char*)dest + i) = *((char*)src + i);
		}
	}

	return dest;
}
char* myStrcpy(char* strDestination, const char* strSource)
{
	assert(strDestination && strSource);
	char* ret = strDestination;
	while (*strDestination++ = *strSource++)
	{
		;
	}

	return ret;
}

这两个放在一起是因为这两个大部分情况是相同的,但是有情况是不同的,比如
 ·

假设str1是一个4个字符的字符串,当把str1,的内容拷贝到str2上时,如果使用memcpy,str2会变成abab,而使用memmove,str2会变成abcd

2.strstr

作用:在主串中匹配字串,返回匹配到的位置。

char* myStrstr(const char* string, const char* strCharSet)
{
	char* ret = NULL;

	const char* begin = string;  //开始匹配的位置
	while (*begin != '\0')
	{
		const char* i = begin;   //主串每一次匹配起点
		const char* j = strCharSet;   //子串每一次匹配起点
		while (*i != '\0' && *j != '\0' && *i == *j)
		{
			i++;
			j++;
		}

		if (*j == '\0')
		{
			//匹配成功
			//记录本次匹配起点
			ret = begin;
			break;
		}
		else
		{
			//匹配失败
			begin++;   //换一个开始匹配的位置
		}
	}

	return ret;
}

在这里我的实现是暴力匹配,时间复杂度为O(m * n),这个实现还可以使用kmp算法将时间复杂度降低至O(m +n),之前我写过kmp的实现,链接如下:
kmp算法实现

3.strlen

此函数之前我也实现过,具体请点击这里

4.strcpy

作用:拷贝字符串。

char* myStrcpy(char* strDestination, const char* strSource)
{
	//将strSource的字符逐个拷贝到strDestination所管理的内存中
	assert(strDestination && strSource);
	char* ret = strDestination;
	while (*strDestination++ = *strSource++)
	{
		;
	}

	return ret;
}

5.strcat

作用:将一个字符串粘贴至另一个字符串末尾

char* myStrcat(char* strDestination, const char* strSource)
{
	assert(strDestination && strSource);
	//移动到strDestination的末尾
	char* str = strDestination;
	while (*str != '\0')
	{
		str++;
	}
	//*str == '\0'
	while (*str++ = *strSource++)
	{
		;
	}

	return strDestination;
}

这个函数首相找到字符串的末尾,之后就和strcpy一样了。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值