本节是string类细节问题
构造与初始化
std::string
有多种构造函数:
cpp
std::string s1; // 默认构造,空字符串
std::string s2("Hello"); // 从C字符串构造
std::string s3(s2); // 拷贝构造
std::string s4(5, 'a'); // 填充构造,结果为"aaaaa"
std::string s5(s2, 1, 3); // 子串构造,从索引1开始取3个字符,结果为"ell"
访问字符
可用[]
或at()
访问字符:
cpp
std::string s = "Hello";
char c1 = s[1]; // 'e',不检查边界
char c2 = s.at(1); // 'e',抛出std::out_of_range异常
修改操作
追加、插入、删除等操作:
cpp
s += " World"; // 追加,s变为"Hello World"
s.append("!"); // 追加,s变为"Hello World!"
s.insert(5, ","); // 插入,s变为"Hello, World!"
s.erase(5, 1); // 删除,s变为"Hello World!"
查找与替换
查找子串或字符:
cpp
size_t pos = s.find("World"); // 返回首次出现的位置(6)
if (pos != std::string::npos) {
s.replace(pos, 5, "C++"); // 替换为"C++",s变为"Hello C++!"
}
容量与大小
cpp
s.size(); // 当前字符数(9)
s.empty(); // 是否为空
s.resize(10); // 调整大小,不足时填充'\0'
s.capacity(); // 当前分配的内存容量
字符串比较
直接使用比较运算符:
cpp
std::string a = "apple", b = "banana";
if (a < b) { /* ... */ } // 字典序比较
转换与C字符串
转换为C风格字符串:
cpp
const char* cstr = s.c_str(); // 返回const char*
char* buf = new char[s.size() + 1];
s.copy(buf, s.size()); // 拷贝到缓冲区
迭代器支持
支持STL迭代器:
cpp
for (auto it = s.begin(); it != s.end(); ++it) {
std::cout << *it;
}
for (char ch : s) { /* ... */ } // 范围for循环
注意:std::string
管理的内存是动态分配的,无需手动释放。C++17后新增了std::string_view
用于非占有式字符串视图。