在 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;
}
以上三种方法都可以实现字符串的连接。你可以根据自己的需求和喜好选择合适的方法。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:如何高效使用c++ string库函数进行字符串操作