模拟实现strlen
//计数器方式 int my_strlen(const char * str) { int count = 0; while(*str) { count++; str++; } return count; }
//不能创建临时变量计数器 int my_strlen(const char * str) { if(*str == '\0') return 0; else return 1+my_strlen(str+1); }
//指针-指针的方式 int my_strlen(const char *s) { char *p = s; while(*p != ‘\0’ ) p++; return p-s; }
模拟实现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; }
模拟实现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; }
模拟实现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 ; }
模拟实现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); }
模拟实现strncpy
char * mystrncpy(char * dst, const char * src, size_t n) { int i; for (i = 0; src[i] && i < n; i++) { dst[i] = src[i]; } if (i < n) { dst[i] = 0; } return dst; }
模拟实现strncat
char * mystrncat(char * dst, const char * src, size_t n) { char * tmp = dst; while (*dst) { dst++; } int i; for (i = 0; src[i] && i < n; i++) { dst[i] = src[i]; } dst[i] = 0; return tmp; }
模拟实现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); }
模拟实现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); }