一、直接使用運算符+
在C++中,我們可以直接使用運算符+來進行字符串相加操作。
#include #include 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 #include #include 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 #include 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 #include 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 #include 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()函數。
原創文章,作者:LMUBK,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/330609.html