strcpy strcat strcmp memcpy函数的自己实现
2019-03-01 13:50 mengjuanjuan1994 阅读(246) 评论(0) 编辑 收藏 举报#include <iostream>
#include <assert.h>
using namespace std;
char* m_strcpy(char* dst, const char* src)
{
assert((dst != NULL) && (src != NULL));
if (dst == src)
{
return dst;
}
char* ret = dst;
int size = strlen(src) + 1;
int len = size;
if(dst > src)
{
dst = dst + size - 1;
src = src + size - 1;
while(size--)
{
*dst-- = *src--;
}
}
else
{
while(size--)
{
*dst++ = *src++;
}
}
return ret;
}
char* m_strcat(char* dst, const char* src)
{
assert(dst);
assert(src);
char* ret = dst;
while(*dst != '\0')
++dst;
int size = strlen(src) + 1;
while (size--)
{
*dst++ = *src++;
}
return ret;
}
void* m_memcpy(void* dst, const char* src, int count)
{
assert(dst);
assert(src);
if (dst == src)
{
return dst;
}
void* ret = dst;
char* pdst = (char*)dst;
char* psrc = (char*)src;
if (pdst > psrc && pdst < psrc + count)
{
pdst = pdst + count -1;
psrc = psrc + count -1;
while (count--)
{
*pdst-- = *psrc--;
}
}
else
{
while (count--)
{
*pdst++ = *psrc++;
}
}
return ret;
}
int m_strcmp(const char* str1, const char* str2)
{
while (*str1 == *str2 && *str1 != '\0' && *str2 != '\0')
{
str1++;
str2++;
}
return *str1 - *str2;
}
int main ()
{
char dst[100] = "hello world";
char *src = "world";
char* ret = (char*)m_memcpy(dst+2, dst, 5);
char* str1 = "abc";
char* str2 = "abcd";
int n = m_strcmp(str2, str1);
system("pause");
return 0;
}