字符串——C++拼接多个字符串
拼接多个字符串在C++的可以通过strcpy_s 和srtcat_s实现,如:
int main() {
char first[10] = {
a,b,c};
char second[] = "hello";
char* third = "world!";
char dest[200];
strcpy_s(dest,first); //这里要先用strcpy_s是因为dest还不是一个字符串,没有
strcat_s(dest, second);
strcat_s(dest, third);
int n = strlen(dest);
cout << n << endl;
for (int i = 0; i < n; i++) {
cout << dest[i];
}
cout<<endl;
return 0;
}
输出
14 abchelloworld!
strcat_s 也可以用C语言直接实现,如:
void copy2(char* to, const char* from) {
char* cp = to;
//找到要拼接的目的字符串的 位置
while (*cp) {
cp++;
}
while (*cp++ = *from++);
}
int main() {
char first[10] = {
a,b,c};
char second[] = "hello";
char* third = "world!";
char dest[200];
dest[0] = ;
copy2(dest, first);
copy2(dest, second);
copy2(dest, third);
int n = strlen(dest);
cout << n << endl;
for (int i = 0; i < n; i++) {
cout << dest[i];
}
cout<<endl;
return 0;
}
输出
14 abchelloworld!
总结:如果要自己实现一个字符串拼接的函数或者方法一定要注意
补充:memcpy()函数也可以实现字符串的拼接
char* str = (char*)malloc(100); memcpy(str,"123",3); //表示在str指针指向内容的前3个位置赋值为“123”,使用这个函数一个要注意后面长度的 //大小,否则会把前面的内容覆盖
