1、字符数组拷贝函数
常用的字符串拷贝函数为strcpy,strncpy,在高版本的中支持安全的拷贝函数:strcpy_s,strncpy_s。
2、函数原型
strcpy函数原型(一):
char *strcpy( char *strDestination,//Destination string. const char *strSource //Null-terminated source string. );
strcpy_s函数原型(一):
3、举例errno_t strcpy_s( char *strDestination,//Location of destination string buffer size_t numberOfElements,//Size of the destination string buffer const char *strSource //Null-terminated source string buffer );
分别利用strcpy和strcpy_s的将二个字符串拼接到另一个字符串。
strcpy version:int main() { char* p1 = "Hello,"; char* p2 = "world!"; int p1Length = strlen(p1); int p2Length = strlen(p2); int totalLengthOfP1AndP2 = p1Length + p2Length; char * concatP1AndP2 = new char[totalLengthOfP1AndP2+1];//add one to store '\0' strcpy(concatP1AndP2,p1); strcpy(concatP1AndP2 + p1Length ,//dest start location:concatP1AndP2 add p1Length p2);//src cout<<"p1:"<<p1<<endl; cout<<"p2:"<<p2<<endl; cout<<"p1+p2:"<<concatP1AndP2<<endl; delete []concatP1AndP2; concatP1AndP2 = NULL; return 0; }strcpy_s version:int main() { char* p1 = "Hello,"; char* p2 = "world!"; int p1Length = strlen(p1); int p2Length = strlen(p2); int totalLengthOfP1AndP2 = p1Length + p2Length; char * concatP1AndP2 = new char[totalLengthOfP1AndP2+1];//add one to store '\0' strcpy_s(concatP1AndP2,//dest p1Length + 1,//number of elements of dest to store src including '\0' p1);//src strcpy_s(concatP1AndP2 + p1Length,//dest start location:concatP1AndP2 add p1Length p2Length + 1,//number of elements of dest to store src including '\0' p2//src ); cout<<"p1:"<<p1<<endl; cout<<"p2:"<<p2<<endl; cout<<"p1+p2:"<<concatP1AndP2<<endl; cout<<"********************************"<<endl; delete []concatP1AndP2; concatP1AndP2 = NULL; return 0; }使用注意事项: strcpy_s中的第二个参数:numberOfElements为至少是src字符串的长度加1('\0'),若不满足此条件,会进行参数校验,提示目标字符串长度不足。 同理,可以使用strncpy和strncpy_s。4、参考
[1] strcpy
[2] strcpy_s
1万+

被折叠的 条评论
为什么被折叠?



