一、直接使用运算符+
在C++中,我们可以直接使用运算符+来进行字符串相加操作。
#include<iostream>
#include<string>
using namespace std;
int main(){
string str1="hello";
string str2="world";
string str3=str1+str2;
cout<<str3<<endl;
return 0;
}
以上代码将输出字符串"helloworld"。
二、使用stringstream
stringstream是C++标准库中的一个类,用于提供各种格式化和解析字符串的工具。
#include<iostream>
#include<sstream>
#include<string>
using namespace std;
int main(){
string str1="hello";
string str2="world";
stringstream ss;
ss<<str1<<str2;
string str3=ss.str();
cout<<str3<<endl;
return 0;
}
以上代码将输出字符串"helloworld"。
三、使用string.append()函数
string类也提供了append()函数,可以用于实现字符串的拼接功能。
#include<iostream>
#include<string>
using namespace std;
int main(){
string str1="hello";
string str2="world";
str1.append(str2);
cout<<str1<<endl;
return 0;
}
以上代码将输出字符串"helloworld"。
四、使用string.insert()函数
string类还提供了insert()函数,可以在指定位置插入字符串。
#include<iostream>
#include<string>
using namespace std;
int main(){
string str1="hello";
string str2="world";
str1.insert(str1.size(),str2);
cout<<str1<<endl;
return 0;
}
以上代码将输出字符串"helloworld"。
五、使用strcpy()函数和strcat()函数
strcpy()函数和strcat()函数是C语言中的库函数,可以用于字符串的复制和拼接。
#include<iostream>
#include<cstring>
using namespace std;
int main(){
char str1[]="hello";
char str2[]="world";
char str3[100];
strcpy(str3,str1);
strcat(str3,str2);
cout<<str3<<endl;
return 0;
}
以上代码将输出字符串"helloworld"。
六、总结
以上是C++实现字符串相加的几种方法。对于简单的字符串拼接,可以使用运算符+或者stringstream类;对于需要插入字符的情况,可以使用insert()函数;对于需要涉及到字符数组的情况,可以使用strcpy()函数和strcat()函数。