模拟实现strcpy,strcat,strstr,strchr,memxpy,memmove

 

 

#include<stdio.h>
#include<assert.h>
#include<windows.h>


char* mystrcpy(char* dest,const char* src)
{
	char* ret = dest;
	assert(dest != NULL);
	assert(src != NULL);
	while((*dest++ = *src++))
	{
		;
	}
	return ret;
}


char* mystrcat(char* dest,const char* src)
{
	char* ret = dest;
	assert(dest != NULL);
    assert(src != NULL);
	while(* dest)
	{
		dest ++;
	}
	while((*dest++ = *src++))
	{
		;
	}
	return ret;
}


char* mystrstr(const char* mstr1,const char* sstr2)
{
	char* ret1 = (char*)mstr1;
	char* ret2 = (char*)sstr2;
	char* start = NULL;
    
	assert(mstr1);
	assert(sstr2);


	if(*sstr2 == '\0')
		return NULL;


	while(*ret1)
	{
		start = ret1;
		ret2 = sstr2;
		while(*ret2)
		{
			if(*start && *ret2 && (*start == *ret2))
			{
				start++;
				ret2++;
			}
			else
			{
				break;
			}
		}
			if(*ret2 == '\0')
				return ret1;
			ret1++;
	}
}


char* mystrchr(const char*dest,char sign)
{
   char *ret1 = (char*)dest;


   assert(dest != NULL);
   while(*dest != NULL)
   {
	   if(*dest == sign)
	   {
		   return dest;
	   }
	   else
	   {
		   dest++;
	   }
   }
   return NULL;


}


void* mymemcpy(void* dest,const void* src,size_t count)
{
	void* ret = dest;


	while(count--)
	{
		*(char*) dest = *(char*) src;
		dest = (char*)dest + 1;
		src = (char*)src + 1;
	}
	return(ret);
}


void* mymemmove(void* dest,const void* src,size_t count)
{
	void *ret = dest;
	if(dest <= src || (char*) dest >= ((char*)src + count))
	{
		while(count --)
		{
           *(char*) dest = *(char*) src;
		   dest = (char*)dest + 1;
		   src = (char*)src + 1;
		}
	}
	else
	{
		dest = (char*)dest + count - 1;
		src = (char*)src + count - 1;
        while(count--)
	{
		*(char*) dest = *(char*) src;
		dest = (char*)dest - 1;
		src = (char*)src - 1;
	}
	}
	return (ret);
}


int main()
{
	char str1[64] = {0};
	const char str2[] = "abcdefg";
	char str3[64] = "hello";
	const char str4[] = "cde";
	char str5[64] = {0};
	int count1 = sizeof(str2) + 1;
	int count2 = sizeof(str3) + 1;
    char* p1 = mystrstr(str2,str4);
	char* p2 = mystrchr(str2,'c');
	 
    mystrcpy(str1,str2);
	mystrcat(str3,str2);
    mymemcpy(str1,str2,count1);
	mymemmove(str5,str3,count2);
	printf("mystrcpy: %s\n",str1);
    printf("mystrcat: %s\n",str3);
	if(p1 != NULL)
	{
		printf("mystrstr: %s\n",p1);
	}
	printf("mystrchr: %s\n",p2);
	printf("mymemcpy(char): %s\n",str1);
	printf("mymemmove: %s\n",str1);


	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值