在C++中,字符串拼接有多种方法,包括使用+运算符、使用+=运算符、使用字符串拼接函数等等。
使用+运算符:
std::string str1 = "Hello";std::string str2 = "World";std::string result = str1 + " " + str2; // 字符串拼接使用+=运算符:
std::string str1 = "Hello";std::string str2 = "World";str1 += " " + str2; // 将str2拼接到str1后面使用字符串拼接函数:
使用strcat函数:char str1[100] = "Hello";char str2[] = "World";strcat(str1, " ");strcat(str1, str2); // 字符串拼接使用stringstream类:#include <sstream>std::string str1 = "Hello";std::string str2 = "World";std::stringstream ss;ss << str1 << " " << str2; // 字符串拼接std::string result = ss.str();需要注意的是,使用字符串拼接函数时,需要确保目标字符串的长度足够长,以避免缓冲区溢出的问题。

