模拟实现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");
}

浙公网安备 33010602011771号