1. 程式人生 > >字元陣列拷貝函式(一)

字元陣列拷貝函式(一)

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、參考