append()是C++中灵活高效的字符串拼接方法,支持多种重载形式,如追加字符串、字符、子串等,相比+运算符更优,推荐结合reserve()预分配空间以提升性能。

在C++中,字符串拼接是常见的操作,std::string 提供了多种方式实现,其中 append() 是一个功能强大且灵活的方法。它不仅可以追加字符串,还能处理子串、字符、C风格字符串(char*)以及指定长度的内容。
append() 是 std::string 的成员函数,用于将内容追加到原字符串末尾。以下是其常见重载形式:
#include <iostream>
#include <string>
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"); // 功能最全,推荐用于复杂场景
在大量拼接时,频繁分配内存会影响效率。可以注意以下几点:
立即学习“C++免费学习笔记(深入)”;
std::string result;
result.reserve(1000); // 预留空间
for (int i = 0; i < 100; ++i) {
result.append("abc");
}
以上就是c++++ 字符串拼接方法 c++ string append用法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号