strcpy,strncpy http://blog.csdn.net/shutear/article/details/8256096

来源:互联网 发布:红苹果预算软件 编辑:程序博客网 时间:2024/04/30 10:14
http://blog.csdn.net/shutear/article/details/8256096
1、字符数组拷贝函数     

常用的字符串拷贝函数为strcpy,strncpy,在高版本的中支持安全的拷贝函数:strcpy_s,strncpy_s。

2、函数原型

strcpy函数原型(一):

[cpp] view plaincopy
  1. char *strcpy(  
  2.    char *strDestination,//Destination string.  
  3.    const char *strSource //Null-terminated source string.  
  4. );  
strcpy_s函数原型(一):
[cpp] view plaincopy
  1. errno_t strcpy_s(  
  2.    char *strDestination,//Location of destination string buffer  
  3.    size_t numberOfElements,//Size of the destination string buffer  
  4.    const char *strSource //Null-terminated source string buffer  
  5. );  
3、举例
   分别利用strcpy和strcpy_s的将二个字符串拼接到另一个字符串。
strcpy version:

[cpp] view plaincopy
  1. int main()  
  2. {  
  3.     char* p1 = "Hello,";  
  4.     char* p2 = "world!";  
  5.   
  6.     int p1Length = strlen(p1);  
  7.     int p2Length = strlen(p2);  
  8.   
  9.     int totalLengthOfP1AndP2 = p1Length + p2Length;  
  10.   
  11.     char * concatP1AndP2 = new char[totalLengthOfP1AndP2+1];//add one to store '\0'  
  12.   
  13.     strcpy(concatP1AndP2,p1);  
  14.     strcpy(concatP1AndP2 + p1Length ,//dest start location:concatP1AndP2 add p1Length  
  15.            p2);//src  
  16.       
  17.     cout<<"p1:"<<p1<<endl;  
  18.     cout<<"p2:"<<p2<<endl;  
  19.     cout<<"p1+p2:"<<concatP1AndP2<<endl;  
  20.   
  21.   
  22.     delete []concatP1AndP2;  
  23.     concatP1AndP2 = NULL;  
  24.   
  25.     return 0;  
  26. }  
strcpy_s version:
[cpp] view plaincopy
  1. int main()  
  2. {  
  3.       
  4.     char* p1 = "Hello,";  
  5.     char* p2 = "world!";  
  6.   
  7.     int p1Length = strlen(p1);  
  8.     int p2Length = strlen(p2);  
  9.   
  10.     int totalLengthOfP1AndP2 = p1Length + p2Length;  
  11.   
  12.     char * concatP1AndP2 = new char[totalLengthOfP1AndP2+1];//add one to store '\0'  
  13.   
  14.     strcpy_s(concatP1AndP2,//dest  
  15.              p1Length + 1,//number of elements of dest to store src including '\0'  
  16.              p1);//src  
  17.   
  18.     strcpy_s(concatP1AndP2 + p1Length,//dest start location:concatP1AndP2 add p1Length  
  19.              p2Length + 1,//number of elements of dest to store src including '\0'  
  20.              p2//src  
  21.             );  
  22.   
  23.     cout<<"p1:"<<p1<<endl;  
  24.     cout<<"p2:"<<p2<<endl;  
  25.     cout<<"p1+p2:"<<concatP1AndP2<<endl;  
  26.   
  27.     cout<<"********************************"<<endl;  
  28.   
  29.   
  30.     delete []concatP1AndP2;  
  31.     concatP1AndP2 = NULL;  
  32.       
  33.     return 0;  
  34. }  
使用注意事项:    strcpy_s中的第二个参数:numberOfElements为至少是src字符串的长度加1('\0'),若不满足此条件,会进行参数校验,提示目标字符串长度不足。同理,可以使用strncpy和strncpy_s。
4、参考
    [1] strcpy
    [2] strcpy_s

版权声明:本文为博主原创文章,未经博主允许不得转载。

0 0
原创粉丝点击