C语言的strcpy函数如何使用

来源:互联网转载和整理 2024-05-16 10:41:39

strcpy函数怎么用

长度不受限制的字符串函数

strcpy

我们看看文档是怎样说的,如下

strcpy文档

char*strcpy(char*destination,constchar*source);

Copy string

字符串拷贝(字符串复制)

Copies the C string pointed bysourceinto the array pointed bydestination, including the terminating null character (and stopping at that point).

复制由字符指针source指向的C字符串到另一个字符数组中,该字符数组字符指针destination指向

To avoid overflows, the size of the array pointed bydestinationshall be long enough to contain the same C string assource(including the terminating null character), and should not overlap in memory withsource.

为避免溢出,由destination指向的字符数组的大小需要足够长,足够包含住源字符串(包含'\0')

综上,可以知道

  1. 会将源字符串中的 '\0' 拷贝到目标空间,源字符串必须以 '\0' 结束。

  2. 目标空间必须足够大,以确保能存放源字符串。

怎么实现拷贝?
intmain(){chararr1[]="abcdefghi";chararr2[]="bit";//把arr2的内容拷贝到arr1中//strcpy(arr1,arr2);//怎么拷贝?my_strcpy(arr1,arr2);printf("%s\n",arr1);return0;}
实现

断言指针不为空是个好习惯~

//char*my_strcpy(char*dest,char*src)//src加上const,为什么?因为我们只需要拷贝,不需要改动源字符串,防止发生修改,所以加上const修饰char*my_strcpy(char*dest,constchar*src){assert(dest!=NULL);assert(src!=NULL);while(*src!='\0'){*dest=*src;dest++;src++;}*dest=*src;//'\0'//返回目的空间的起始地址returndest;}

源字符串拷贝到目的空间,寻找'\0',不是'\0'的就执行*dest = *src,把源字符赋值给目的空间,然后两个指针都往后偏移,也就是都进行++,当*src为'\0'时,说明源字符串已经到结尾了,就退出这个循环,直接将'\0'赋值给*dest,最后返回dest

可以进行优化,如下

char*my_strcpy(char*dest,constchar*src){assert(dest!=NULL);assert(src!=NULL);//优化while(*src!='\0'){*dest++=*src++;}*dest=*src;//'\0'//返回目的空间的起始地址returndest;}

当然还可以继续优化,变得更加简洁,直接将*dest++ = *src++作为判断条件,同时还会执行操作,如下

char*my_strcpy(char*dest,constchar*src){assert(dest!=NULL);assert(src!=NULL);//优化//拷贝src指向的字符串到dest指向的空间,包含'\0'char*rest=dest;while(*dest++=*src++){;}//返回目的空间的起始地址returnrest;}