模拟实现strncpy与极简改进

模拟实现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");
}
posted @ 2017-03-16 20:43  乐天的java  阅读(44)  评论(0)    收藏  举报