标签:strcmp strcat strcpy strstr memcpy memmove
//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 ,若dst<src,即dst在src前面,则没有重叠。 //若dst>src,即dst在src后面,此时若srt+count<dst,则没有重叠。 //若dst>src,即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; }
本文出自 “printf的返回值” 博客,请务必保留此出处http://10741125.blog.51cto.com/10731125/1782572
模拟实现部分库函数(strcpy,strcmp,strcat,strstr,memcpy,memmove,memset)
标签:strcmp strcat strcpy strstr memcpy memmove
原文地址:http://10741125.blog.51cto.com/10731125/1782572