c标准库函数实现源码
1)字符串拷贝
1. 2. 3. 4. 5. 6. 7. 8.
char * strcpy( char *strDest, const char *strSrc ) {
if(strDest == strSrc) { return strDest; }
assert( (strDest != NULL) && (strSrc != NULL) ); char *address = strDest;
while( (*strDest++ = * strSrc++) != '/0' ); return address; }
1. //字串末尾要加结束符'/0',不然输出错位结果
2. char *strncpy(char *strDes, const char *strSrc, unsigned int count) 3. {
4. assert(strDes != NULL && strSrc != NULL); 5. char *address = strDes;
6. while (count-- && *strSrc != '/0') 7. *strDes++ = *strSrc++; 8. *strDes = '/0';
9. return address; 10. }
2)字符串比较
1. int strcmp(const char *s, const char *t) 2. {
3. assert(s != NULL && t != NULL); 4. while (*s && *t && *s == *t) 5. {
6. ++ s; 7. ++ t; 8. }
9. return (*s - *t); 10. } 11.
12. int strncmp(const char *s, const char *t, unsigned int count) 13. { assert((s != NULL) && (t != NULL)); 14. while (*s && *t && *s == *t && count --)
15. { ++ s; ++ t; }
16. return (*s - *t); 17. } 3)字符串连接
1. char *strcat(char *strDes, const char *strSrc) 2. {
3. assert((strDes != NULL) && (strSrc != NULL)); 4. char *address = strDes; 5. while (*strDes != '/0') 6. ++ strDes;
7. while ((*strDes ++ = *strSrc ++) != '/0') 8. NULL;
9. return address; 10. } 1. char *strncat(char *strDes, const char *strSrc, unsigned int count) 2. {
3. assert((strDes != NULL) && (strSrc != NULL)); 4. char *address = strDes; 5. while (*strDes != '/0') 6. ++ strDes;
7. while (count -- && *strSrc != '/0' ) 8. *strDes ++ = *strSrc ++; 9. *strDes = '/0'; 10. return address; 11. }
4)字符串长度
1. 2. 3. 4. 5. 6. 7. 8.
int strlen(const char *str) {
assert(str != NULL); int len = 0;
while (*str ++ != '/0') ++ len; return len; }
5)字符串匹配
1. 2. 3. 4.
char *strstr(const char *strSrc, const char *str) {
assert(strSrc != NULL && str != NULL); const char *s = strSrc;
const char *t = str;
for (; *strSrc != '/0'; ++ strSrc) {
for (s = strSrc, t = str; *t != '/0' && *s == *t; ++s, ++t)
9. NULL; 10. if (*t == '/0') 11. return (char *) strSrc; 12. } 13. return NULL; 14. }
5. 6. 7. 8.
6)内存块复制
1. void *memcpy(void *dest, const void *src, unsigned int count) 2. {
3. assert((dest != NULL) && (src != NULL)); 4. void *address = dest; 5. while (count --) 6. {
7. *(char *) dest = *(char *) src; 8. dest = (char *) dest + 1; 9. src = (char *) src + 1; 10. } 11. return address; 12. }
7)内存块赋值初始化
1. void *memset(void *str, int c, unsigned int count) 2. {
3. assert(str != NULL); 4. void *s = str; 5. while (count --) 6. {
7. *(char *) s = (char) c; 8. s = (char *) s + 1; 9. } 10. return str; 11. }