append()是C++中灵活高效的字符串拼接方法,支持多种重载形式,如追加字符串、字符、子串等,相比+运算符更优,推荐结合reserve()预分配空间以提升性能。
在C++中,字符串拼接是常见的操作,std::string 提供了多种方式实现,其中 append() 是一个功能强大且灵活的方法。它不仅可以追加字符串,还能处理子串、字符、C风格字符串(char*)以及指定长度的内容。
append() 是 std::string 的成员函数,用于将内容追加到原字符串末尾。以下是其常见重载形式:
#include#include int main() { std::string s = "Hello"; s.append(" World"); // 结果: "Hello World" std::cout << s << std::endl; s.append(3, '!'); // 追加3个'!' → "Hello World!!!" std::cout << s << std::endl; std::string sub = "abcdef"; s.append(sub, 0, 3); // 从sub取前3个字符 → "abc" std::cout << s << std::endl; return 0; }
除了 append(),C++ 中还有其他常用拼接方法:
std::string a = "Hello"; a += " World"; // 推荐用于简单追加 std::string b = "Hello"; b = b + " World"; //可行,但会创建临时对象 std::string c = "Hello"; c.append(" World"); // 功能最全,推荐用于复杂场景
在大量拼接时,频繁分配内存会影响效率。可以注意以下几点:
std::string result;
result.reserve(1000); // 预留空间
for (int i = 0; i < 100; ++i) {
result.append("abc");
}
基本上就这些。append 方法灵活高效,适合大多数字符串追加需求。