使用operator+可直观拼接字符串,但频繁使用可能影响性能;2. append()成员函数能高效追加内容,适合动态构建;3. stringstream支持拼接不同类型数据,方便灵活。

在C++中拼接多个字符串有多种方式,选择合适的方法能提高代码的可读性和效率。下面介绍几种常用且实用的字符串拼接方法。
使用 operator+ 拼接字符串
对于std::string类型,可以直接使用+或+=操作符进行拼接,这是最直观的方式。
示例:
std::string a = "Hello"; std::string b = " "; std::string c = "World"; std::string result = a + b + c; // "Hello World" a += "!";
这种方式适合少量字符串拼接,但频繁使用+可能产生临时对象,影响性能。
立即学习“C++免费学习笔记(深入)”;
使用 append() 成员函数
append()是std::string提供的成员函数,可以在原字符串末尾追加内容,避免多次创建临时对象。
示例:
std::string str = "Hello";
str.append(" ");
str.append("World");
// str 变为 "Hello World"
支持追加字符串、字符、子串或指定长度的内容,适合动态构建字符串。
使用 stringstream 拼接不同类型数据
当需要拼接字符串和数字等非字符串类型时,std::stringstream非常方便。
示例:
#includestd::stringstream ss; ss << "Age: " << 25 << ", Score: " << 98.5; std::string result = ss.str(); // "Age: 25, Score: 98.5"
尤其适用于混合类型拼接,代码清晰且不易出错。
使用 C++14 的 string literal 结合 operator""s
C++14引入了字符串字面量后缀s,可以让字符串字面量自动转为std::string,简化拼接。
示例:
using namespace std::string_literals; auto str = "Hello"s + " " + "World"s;
避免了字符数组与std::string混用时的隐式转换问题,提升类型安全。
基本上就这些。根据场景选择:简单拼接用+,大量追加用append(),混合类型用stringstream,现代C++可考虑字面量。不复杂但容易忽略细节。











