string
std::string 是 C++ 标准库中的字符串类,用来管理可变长度文本。
和 C 风格字符串(char*、char[])相比,string 自动管理内存,提供了更安全、更直观的接口。
头文件与基本特征
使用 string 时,需要包含:
#include <string>
常见特征:
| 特征 | 说明 |
|---|---|
| 底层存储 | 字符序列 |
| 长度管理 | 自动维护长度 |
| 可修改 | 支持插入、删除、替换 |
| 兼容 C 字符串 | 可通过 c_str() 获取 const char* |
基本用法
#include <iostream>
#include <string>
int main() {
std::string s1 = "hello";
std::string s2 = "world";
std::string s3 = s1 + " " + s2;
std::cout << s3 << '\n';
return 0;
}
常用成员函数
| 函数 | 作用 |
|---|---|
size() / length() | 返回字符串长度 |
empty() | 判断是否为空 |
clear() | 清空字符串 |
append() | 追加内容 |
insert() | 插入子串 |
erase() | 删除子串 |
replace() | 替换子串 |
find() | 查找子串或字符 |
substr() | 提取子串 |
c_str() | 获取 C 风格只读字符串 |
查找与截取
#include <iostream>
#include <string>
int main() {
std::string text = "C++ standard library";
std::string key = "standard";
std::string::size_type pos = text.find(key);
if (pos != std::string::npos) {
std::cout << "found at " << pos << '\n';
std::cout << text.substr(pos, key.size()) << '\n';
}
return 0;
}
find 找不到时返回 std::string::npos。
修改示例
#include <iostream>
#include <string>
int main() {
std::string s = "I like C";
s.append("++"); // I like C++
s.replace(7, 3, "modern C++"); // I like modern C++
std::cout << s << '\n';
return 0;
}
string 与 C 字符串
string更安全,不需要手动管理结尾\0。- 需要调用 C 接口时可用
c_str()。 - C++98 时代很多旧 API 仍要求
const char*,此时桥接很常见。
使用注意
operator[]不做边界检查;at()会检查边界。- 对字符串频繁拼接时,直接用
+也可读性很高;超大规模拼接可考虑ostringstream。 - 对返回位置索引建议使用
std::string::size_type。