常见字符串函数实现

Posted 我是晓伍

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了常见字符串函数实现相关的知识,希望对你有一定的参考价值。

今天模拟实现了一些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一样了。

以上是关于常见字符串函数实现的主要内容,如果未能解决你的问题,请参考以下文章

常见字符串函数实现

常见字符串函数实现

常见字符串函数实现

常见字符串函数实现

C语言常见字符串库函数的使用与实现

C语言常见字符串函数实现