手写strcpy、strlen、strcmp、strcat、memcpy、memmove、memset

1、strcpy

char* strcpy(char* dest, const char* src) {
    assert(dest != NULL && src != NULL);
    char* begin = dest;
    while (*src != '\0') {
        *dest = *src;
        ++dest;
        ++src;
    }
    return begin;
}

如果不写assert,则没有判断异常情况,dest的末尾没有赋 '\0'
正确写法:

char* strcpy(char* dest, const char* src) {
    assert(dest != NULL && src != NULL);
    char* begin = dest;
    while ((*dest++ = *src++) != '\0') 
    ;
    return begin;
}

引自:https://baike.baidu.com/item/strcpy/5494519?fr=aladdin

2、strlen

size_t strlen(const char * str) {
    assert(str == NULL)
    size_t len = 0;
    while (*str++ != '\0') {
        ++len;
    }
    return len;
}

3、strcmp

int strcmp(const char *s1 const char *s2) {
    assert((s1 != NULL) && (s2 != NULL));
    
    while (*s1 == *s2) {
        if (*s1 == '\0')
            return 0;
        
        ++s1;
        ++s2;
    }
    
    return *s1 - *s2;
}

4、strcat

char* strcat(const char *dest, const char *src) {
    assert((dest != NULL) && (src != NULL));
    
    char *ret = dest;
    while (*dest != '\0') {
        ++dest;
    }
    
    while ((*dest++ = *src++) != '\0')
        ;
    return ret;
}

引自:https://baike.baidu.com/item/strcat

引自:https://songlee24.github.io/2015/03/15/string-operating-function/

5、memcpy

void* memcpy(void *dst, const void *src, size_t size) {
    char *s_dst = (char *)dst;
    char *s_src = (char *)src;
    if (s_dst == NULL || s_src == NULL)
        return NULL;
    
    if (s_src < s_dst && s_src + size > s_dst) { //考虑地址重叠,且dst的地址高于src的地址的情况
        s_dst = s_dst + size - 1;
        s_src = s_src + size - 1;
        while(size--) {
            *s_dst-- = *s_src--;
        }
    } else {  //考虑地址不重叠,或者地址重叠,且dst的地址低于src地址的情况
        while (size--) {
            *s_dst++ = *s_src++;
        }
    }
    return dst;
}

引自:https://zhuanlan.zhihu.com/p/70873246
https://blog.csdn.net/Li_Ning_/article/details/51418400

6 memset

void* memset(void *dst, int val, size_t size) {
    char *s_dst = dst;
    char ch = val;
    if (s_dst == NULL) {
        return NULL;
    }
    
    while (size--) {
        *s_dst++ = ch;
    }
    
    return dst;
}

https://blog.csdn.net/u013009575/article/details/17584267

你可能感兴趣的:(手写strcpy、strlen、strcmp、strcat、memcpy、memmove、memset)