2. 库函数的模拟实现
2.1 模拟实现strlen
三种方式:
方式1:
//计数器方式 int my_strlen(const char * str) { int count = 0; while(*str) { count++; str++; } return count; }
方式2:
//不能创建临时变量计数器 int my_strlen(const char * str) { if(*str == '\0') return 0; else return 1+my_strlen(str+1); }
方式3:
//指针-指针的方式 int my_strlen(char *s) { char *p = s; while(*p != ‘\0’ ) p++; return p-s; }
2.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; }
2.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; }
2.4 模拟实现strstr
注:让他们下去自己研究一下KMP算法
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); }
2.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 ); }
2.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); }
2.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); }