在 C++ 中,你可以使用 std::string 库中的函数来连接字符串。以下是一些常用的方法:
+ 运算符连接字符串:#include <iostream>
#include <string>
int main() {
std::string str1 = "Hello, ";
std::string str2 = "World!";
std::string result = str1 + str2;
std::cout << result << std::endl; // 输出 "Hello, World!"
return 0;
}
append() 函数连接字符串:#include <iostream>
#include <string>
int main() {
std::string str1 = "Hello, ";
std::string str2 = "World!";
std::string result = str1.append(str2);
std::cout << result << std::endl; // 输出 "Hello, World!"
return 0;
}
std::stringstream 来连接字符串:#include <iostream>
#include <sstream>
#include <string>
int main() {
std::string str1 = "Hello, ";
std::string str2 = "World!";
std::stringstream ss;
ss << str1 << str2;
std::string result = ss.str();
std::cout << result << std::endl; // 输出 "Hello, World!"
return 0;
}
以上三种方法都可以实现字符串的连接。你可以根据自己的需求和喜好选择合适的方法。