//1.strcpy(拷贝)
char* my_strcpy(char*dst, const char*src)
{
assert(dst);
assert(src);
char* cp = dst;
while (*cp++ = *src++)
{
;
}
return dst;
}
//2.strcat(连接)
char* my_strcat(char*dst, const char*src)
{
assert(dst);
assert(src);
char* cp = dst;
while (*cp != '\0')
{
cp++;
}
while (*cp++ = *src++)
{
;
}
return dst;
}
//3.strcmp(比较)
int my_strcmp(const char*dst, const char*src)
{
assert(dst);
assert(src);
int ret = 0;
while (!(ret=*(unsigned char*)dst - *(unsigned char*)src) && *dst)
{
dst++;
src++;
}
if (ret > 0)
{
ret = 1;
}
else if (ret < 0)
{
ret = -1;
}
return ret;
}
//4.strstr (寻找子串)
char* my_strstr(const char*dst, const char*src)
{
char* cp = (char*)src;
char*s1;
char*s2;
if (!*dst)
{
return ((char*)src);
}
while (*cp)
{
s1 = cp;
s2 = (char*)dst;
while (!(*s1-*s2)&&*s1&&s2)
{
s1++;
s2++;
}
if (!*s2)
{
return (cp);
}
cp++;
}
return (NULL);
}
//5.memcpy(内存拷贝,不重叠)
void* my_memcpy(void *dst, const void*src, size_t count)
{
assert(dst);
assert(src);
char*ret = (char*)dst;
while (count--)
{
*(char*)dst = *(char*)src;
dst = (char*)dst + 1;
src = (char*)src + 1;
}
return ret;
}
//6.memmove(内存移动,实现重叠拷贝)
//内存移动有两种情况:如有一字符串:abcdefgh ,若dstsrc,即dst在src后面,此时若srt+countsrc,即dst在src后面,此时若srt+count>dst,则有重叠,此时需从后向前,由src+count开始拷贝到dst+count。
void *my_memmove(void*dst, const void*src, size_t count)
{
assert(dst);
assert(src);
void *ret = dst;
if ((dst < src) || ((char*)src + count) < (char*)dst) //内存不重叠,顺着按顺序拷贝
{
while (count--)
{
*(char*)dst = *(char*)src;
dst = (char*)dst + 1;
src = (char*)src + 1;
}
}
else //内存有重叠,则倒着拷贝
{
dst = (char*)dst + count - 1;
src = (char*)src + count - 1;
while (count--)
{
*(char*)dst = *(char*)src;
dst = (char*)dst - 1;
src = (char*)src - 1;
}
}
return ret;
}
//7.memset(内存设置)
void* my_memset(void*dst, int val, size_t count)
{
void*start = dst;
while (count--)
{
*(char*)dst = (char)val;
dst = (char*)dst + 1;
}
return start;
}
网站题目:模拟实现部分库函数(strcpy,strcmp,strcat,strstr,memcpy,memmove,memset)
当前URL:
http://cdxtjz.cn/article/jjpsec.html