字符串复制函数:

strcpy(目标字符串的首地址,被复制的字符串的首地址)

  复制p到a:
char * p="12345"; char a[20]; strcpy(a, p); printf("%s\n", a);

 strcpy_s(目标字符串的首地址,缓冲长度,被复制的字符串的首地址)
strcpy_s(a, 20, p);//20为缓冲长度 可用空间的长度 printf("%s\n", a);

strncpy(目标字符串的首地址,被复制的字符串的首地址,复制的长度) ,这种复制方式更像是覆盖
strncpy(a, "123456", 4);
strncpy_s(目标字符串的首地址,缓冲长度,被复制的字符串的首地址,,复制的长度),清零后复制
strncpy_s(a, 20, "123456", 4);
仿真字符串复制函数 strcpy
char* my_strcpy(char* dest, const char* src); char* my_strcpy(char* dest,
const char* src) { char* p_dest = dest; const char* p_src = src; while
(*p_src)//!='\0' { *p_dest = *p_src; p_src++; p_dest++; } *p_dest = '\0';
return dest; }
测试:
printf("%s\n", my_strcpy(a, "how are you"));
仿真字符串复制函数 strncpy
char* my_strncpy(char* dest, const char* src, unsigned num); char*
my_strncpy(char* dest, const char* src, unsigned num) { char* p_dest = dest;
const char* p_src = src; int i = 0; while (*p_src && i++ < num)//!='\0' {
*p_dest = *p_src; p_src++; p_dest++; } //*p_dest = '\0'; return dest; }
测试:
my_strncpy(a, "123456", 4);

完整代码:
#include <stdio.h> #include <string.h> char* my_strcpy(char* dest, const char*
src); char* my_strncpy(char* dest, const char* src, unsigned num); int main ()
{ /*字符串复制函数*/ char * p="12345"; char a[20]; /*strcpy*/ //a=p; strcpy(a, p);
printf("%s\n", a); printf("%s\n", my_strcpy(a, "how are you")); printf("%d\n",
strlen(strcpy(a, "how old are you"))); /*strcpy_s*/ strcpy_s(a, 20,
p);//20为缓冲长度 可用空间的长度 printf("%s\n", a); /*strncpy*/ my_strncpy(a, "123456",
4);//像是覆盖 strncpy(a, "123456", 4);//像是覆盖 printf("%s\n", a); /*strncpy_s*/
strncpy_s(a, 20, "123456", 4);//清零后复制 printf("%s\n", a); /*仿真字符串复制函数 strcpy */
return 0; } char* my_strcpy(char* dest, const char* src) { char* p_dest = dest;
const char* p_src = src; while (*p_src)//!='\0' { *p_dest = *p_src; p_src++;
p_dest++; } *p_dest = '\0'; return dest; } char* my_strncpy(char* dest, const
char* src, unsigned num) { char* p_dest = dest; const char* p_src = src; int i
= 0; while (*p_src && i++ < num)//!='\0' { *p_dest = *p_src; p_src++; p_dest++;
} //*p_dest = '\0'; return dest; }
完整输出:

 

技术
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:[email protected]
QQ群:766591547
关注微信