c语言cpy(str c),c语言str_cpy和strn_cpy实现

#include

#include

char* my_strcpy(char *dest,const char* source){

assert(dest!=NULL||source!=NULL);

//store the address start of the dest string

char* res=dest;

while((*dest++=*source++)!='\0');

return res;

}

int main(){

char src[10]="qwertyuio";

char dest[13];

printf("%s",my_strcpy(dest,src));

return 0;

}

char * strncpy ( char * destination, const char * source, size_t num );

Copy characters from string Copies the first

num characters of

source to

destination. If the end of the

source C string (which is signaled by a null-character) is found before

num characters have been copied,

destination is padded with zeros until a total of

num characters have been written to it.

No null-character is implicitly appended at the end of

destination if

source is longer than

num. Thus, in this case,

destination shall not be considered a null terminated C string (reading it as such would overflow).英文描述引用自

http://www.cplusplus.com/reference/cstring/strncpy/

从source字符串中拷贝num个字符到目标字符窜。如果在拷贝完num个字符之前源字符串的末尾(即'\0'空字符)就遇到了(src字符串长度比num小),那么目标字符串将用0填充直到填满num个字符

如果源字符串比num长,那么非空字符'\0'不会附加到目标字符串。这种情形下,目标字符串不应该被认为是以空字符结束的字符串

#include

char *my_strncpy(char * dest,const char * source,size_t num){

char *res=dest;

while(num--&&(*dest++=*source++)!='\0');

while(num--)

*dest++='\0';

return res;

}

int main(){

char src[10]="qwertyuio";

char dest[13];

printf("%s",my_strncpy(dest,src,12));

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值