当前位置: 首页 > 工具软件 > cpy > 使用案例 >

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

龚彬
2023-12-01

#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;

}

 类似资料: