前言
今天恒川带给大家的是平常应用的库函数,恒川来给大家都模拟实现一下,希望对大家有帮助!!
各大常用库函数的模拟实现
1. 模拟实现strlen2. 模拟实现strcpy3. 模拟实现strcat4. 模拟实现strstr5. 模拟实现strcmp6. 模拟实现memcpy7. 模拟实现memmove
1. 模拟实现strlen
三种方式:
方式1:
//计数器方式int my_strlen(const char* str){int count = 0;while (*str){count++;str++;}return count;}int main(){int len = my_strlen("abcdef");printf("%d\n", len);return 0;}
方式2:
//不能创建临时变量计数器//递归int my_strlen(const char* str){if (*str == '\0')return 0;elsereturn 1 + my_strlen(str + 1);}int main(){int len = my_strlen("abcdef");printf("%d\n", len);return 0;}
方式3:
//指针-指针的方式int my_strlen(char* str){char* start = str;while (*str != '\0')str++;return str - start;//指针-指针得到的是元素个数}int main(){int len = my_strlen("abcdef");printf("%d\n", len);return 0;}
2. 模拟实现strcpy
参考代码:
//1.参数顺序//2.函数的功能,停止条件//3.assert//4.const修饰指针//5.函数返回值//6.题目出自《高质量C/C++编程》书籍最后的试题部分char* my_strcpy(char* dest, const char* src){char* ret = dest;assert(dest != NULL);assert(src != NULL);while ((*dest++ = *src++)){;}return ret;}
3. 模拟实现strcat
参考代码:
char* my_strcat(char* dest, const char* src){char* ret = dest;assert(dest != NULL);assert(src != NULL);while (*dest){dest++;}while ((*dest++ = *src++)){;}return ret;}
4. 模拟实现strstr
char* strstr(const char* str1, const char* str2){char* cp = (char*)str1;char* s1, * s2;if (!*str2)return((char*)str1);while (*cp){s1 = cp;s2 = (char*)str2;while (*s1 && *s2 && !(*s1 - *s2))s1++, s2++;if (!*s2)return(cp);cp++;}return(NULL);}
5. 模拟实现strcmp
参考代码:
int my_strcmp(const char* src, const char* dst){int ret = 0;assert(src != NULL);assert(dest != NULL);while (!(ret = *(unsigned char*)src - *(unsigned char*)dst) && *dst)++src, ++dst;if (ret < 0)ret = -1;else if (ret > 0)ret = 1;return(ret);}
6. 模拟实现memcpy
参考代码:
void* memcpy(void* dst, const void* src, size_t count){void* ret = dst;assert(dst);assert(src); /* * copy from lower addresses to higher addresses */while (count--) {*(char*)dst = *(char*)src;dst = (char*)dst + 1;src = (char*)src + 1;}return(ret);}
7. 模拟实现memmove
参考代码:
void* memmove(void* dst, const void* src, size_t count){void* ret = dst;if (dst <= src || (char*)dst >= ((char*)src + count)) { /* * Non-Overlapping Buffers* * copy from lower addresses to higher addresses */while (count--) {*(char*)dst = *(char*)src;dst = (char*)dst + 1;src = (char*)src + 1;}}else { /* * Overlapping Buffers * copy from higher addresses to lower addresses */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);}
如果这份博客对大家有帮助,希望各位给恒川一个免费的点赞作为鼓励,并评论收藏一下,谢谢大家!!!
制作不易,如果大家有什么疑问或给恒川的意见,欢迎评论区留言。