字符数组拷贝函数(一)

1、字符数组拷贝函数     

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

2、函数原型

strcpy函数原型(一):

char *strcpy(
   char *strDestination,//Destination string.
   const char *strSource //Null-terminated source string.
);

strcpy_s函数原型(一):
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
);
3、举例
   分别利用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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值