模拟实现strncpy与极简改进

来源:互联网 发布:dreamweaver是什么软件 编辑:程序博客网 时间:2024/05/16 05:12

模拟实现strncpy与极简改进
代码如下:

#include<stdio.h>#include<string.h>#include<assert.h>char *mystrncpy(char *des, const char *src, size_t n){    assert(des != NULL);    assert(src != NULL);    size_t len = strlen(des);    char* s = des;    if (n <= len)    {        while (n--)        {            *(s++) = *(src++);        }        *s = '\0';    }else    {        while (*s++ = *src++);    }    return des;}int main(){    char arr[] = "aaaaa";    char brr[] = "bbbb";    int n = 100;    char *b=mystrncpy(arr, brr, n);    printf("%s", b);    system("pause");"%s", b);system("pause");

}
极简修改版:

#include<stdio.h>#include<string.h>#include<assert.h>char *mystrncpy(char *des, const char *src, size_t n){    assert(des != NULL);    assert(src != NULL);    int len = strlen(des);    char* s = des;    while (n-- && (*s++ = *src++));    if ((*s) != '\0')    {        *s = '\0';    }    return des;}int main(){    char arr[] = "aaaaa";    char brr[] = "bbbb";    int n = 100;    char *b=mystrncpy(arr, brr, n);    printf("%s", b);    system("pause");}
0 0
原创粉丝点击