1、strlen
非递归版本
int strlen(const char *s) { assert(s!=NULL); const char *p=s; while(*p)p++; return p-s; }
递归版本
int strlen(const char *s) { return *s?1+strlen(s+1):0; }
2、strcat
char *strcat(char *s,const char *p) { assert(s!=NULL && p!=NULL); char *q=s; while(*q)q++; while((*q++=*p++)); return s; }
char *strncat(char *s,const char*p,size_t n) { assert(s!=NULL && p!=NULL); char *q=s; while(*q)q++; while(n-- && (*q++=*p++)!=‘\0‘); *q=0; return s; }
3、strcpy
char *strcpy(char *d,const char *s) { assert(s!=NULL && d!=NULL); if(d==s) return d; char *p=d; while((*p++=*s++)); return d; }
char *strncpy(char *d,const char *s,size_t n) { assert(s!=NULL && d!=NULL); char *p=d; while(n-- && (*p++=*s++)!=‘\0‘); *p=0; return d; }
4、strcmp
int strcmp(const char *s,const char *d) { assert(s!=NULL && d!=NULL); int result=0; while(!(result=*s-*d)&&*s&&*d) s++,d++; if(result>0) result=1; else if(result<0) result=-1; else result=0; return result; }
int strncmp(const char *s,const char* p,size_t n) { assert(s!=NULL && p!=NULL); int result=0; while(n-- && !(result=*s-*p) && *s && *p) s++,p++; if(result < 0) result=-1; else if(result >0) result=1; else result=0; return result; }
5、strstr
char *strstr(const char *s,const char *p) { assert(s!=NULL && p!=NULL); while(*s) { const char *q=s; const char *r=p; while(*q==*r && *r) q++,r++; if(*r==‘\0‘) return (char*)s; s++; } return NULL; }
6、strchr
char *strchr(const char*s,int c) { assert(s!=NULL); while(*s) { if(*s==(char)c) return (char*)s; s++; } return NULL; }
7、memmove
void *memmove(void *d,const void *s,size_t n) { assert(s!=NULL && d!=NULL); char *p=(char *)d; const char *q=(const char*)s; if(p>q && p<q+n) { p=p+n-1; q=q+n-1; while(n--)*p--=*q--; } else { while(n--)*p++=*q++; } return d; }
8、memcpy
void *memcpy(void *d,const void *s,size_t n) { assert(s!=NULL && d!=NULL); char *p=(char *)d; const char *q=(const char *)s; while(n--) *p++=*q++; return d; }
9、memcmp
int memcmp(const void *s,const void *d,size_t n) { assert(s!=NULL && d!=NULL); const char *p=(const char*)s; const char *q=(const char*)d; int result=0; while(n-- && !(result=*p-*q)) p++,q++; if(result>0) result=1; else if(result<0) result=-1; return result; }
10、memset
void *memset(void *s,int c,size_t n) { assert(s!=NULL); char *p=(char *)s; while(n--) *p++=c; return s; }
原文:http://www.cnblogs.com/luosongchao/p/3683588.html