c语言str_cpy和strn_cpy实现

来源:互联网 发布:厦门大学网络继续教育 编辑:程序博客网 时间:2024/06/12 22:24

#include<stdio.h>#include<assert.h>char* my_strcpy(char *dest,const char* source){assert(dest!=NULL||source!=NULL);//store the address start of the dest stringchar* 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 ofnum 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<stdio.h>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;}






原创粉丝点击