简单的介绍5 种字符串拷贝的方法:

简单的介绍5 种字符串拷贝的方法:

1、char * strcopy_1(char * dest, char * scr)

char * strcopy_1(char * dest, char * scr)
{
    if (dest == NULL || scr == NULL)
    {
        return NULL;
    }

    char * temp = dest;
    while (*temp++ = *scr++);

    return dest;
}

2、char * strcopy_2(char * dest, char * scr)

char * strcopy_2(char * dest, char * scr)
{
    if (dest == NULL || scr == NULL)
    {
        return NULL;
    }

    unsigned int len = strlen(scr) + 1;

    while (*dest++ = *scr++);

    return dest - len;
}

3、char * strcopy_3(char * dest, char * scr)

char * strcopy_3(char * dest, char * scr)
{
    if (dest == NULL || scr == NULL)
    {
        return NULL;
    }

    memcpy(dest, scr, strlen(scr) + 1);

    return dest;
}  

4、char * strcopy_4(char * dest, char * scr)

char * strcopy_4(char * dest, char * scr)
{
    if (dest == NULL || scr == NULL)
    {
        return NULL;
    }

    for (unsigned int i = 0; i < strlen(scr) + 1; i++)
    {
        dest[i] = scr[i];
    }

    return dest;
}

5、char * strcopy_5(char * dest, char * scr)

char * strcopy_5(char * dest, char * scr, int len = 0)
{
    if (dest == NULL || scr == NULL)
    {
        return NULL;
    }

    *dest = *scr;

    if (*scr == '\0')
    {
        return dest - len;
    }

    return strcopy_5(dest + 1, scr + 1, len + 1);
}

写个main函数调用一下:

int main()
{
    char * strScr = "Hello World";
    char strDest[MAX_LEN];

    printf("%s\n", strcopy_1(strDest, strScr));
    printf("%s\n", strcopy_2(strDest, strScr));
    printf("%s\n", strcopy_3(strDest, strScr));
    printf("%s\n", strcopy_4(strDest, strScr));
    printf("%s\n", strcopy_5(strDest, strScr));
    return 0;
}

输出结果为:
简单的介绍5 种字符串拷贝的方法:_第1张图片

你可能感兴趣的:(C/C++)