C++ <string>
系统介绍 std::string 的声明初始化、拼接访问、子串截取与查找替换、增删清空、C 字符串互操作及字符集搜索等 20 个核心成员函数,并在离线 G++ C++17 容器完整实测。
学完这一章,你能够
- 系统介绍 std::string 的声明初始化、拼接访问、子串截取与查找替换、增删清空、C 字符串互操作及字符集搜索等 20 个核心成员函数,并在离线 G++ C++17 容器完整实测。
std::string 定位与基本声明拼接语法
头文件 `<string>` 定义了动态字符序列类 `std::string`(实为 `std::basic_string<char>` 的类型别名)。相比以 `\0` 结尾、需手动管理缓冲区容量的 C 风格字符数组,`std::string` 自动管理内存生命周期、自带长度记录并支持丰富的安全字符串操作。使用前引入 `#include <string>` 即可。
最基础的三类语法是:声明空字符串 `std::string str;`;以字符串字面量直接初始化 `std::string str = "Hello, World!";`;以及使用 `+` 运算符将多个字符串拼接生成新字符串 `std::string result = str1 + str2;`。
核心成员函数与基础实践示例
日常最高频的成员函数包括:`size()`(及等价别名 `length()`)返回字节长度;`empty()` 判断是否为空串;`operator[]` 按下标快速读取或修改字符(不检查越界,需越界抛 `std::out_of_range` 时改用 `at()`);`substr(pos, count)` 截取子串;`find()` 搜索子串首次出现位置(未命中返回 `std::string::npos`);`replace(pos, len, str)` 原地替换指定区段。
基础示例对 `"Hello, World!"` 依次完成长度查询(`13`)、非空判定、`greeting[7] == 'W'` 访问、`substr(7, 5)` 截取 `"World"`、`find("World") == 7` 定位,以及在确认 `pos != std::string::npos` 后将其替换为 `"Hello, C++!"`。
完整成员函数体系与字符集搜索实测
除上述接口外,`std::string` 还提供反向查找 `rfind()`、尾部追加 `append()`、定点插入 `insert()`、区间删除 `erase()`、清空 `clear()`、字典序比较 `compare()`、与 C API 互操作的 `c_str()` / `data()`(自 C++11 起两者均保证末尾附带空终止符 `\0`),以及面向字符集合的四件套搜索方法:`find_first_of`、`find_last_of`、`find_first_not_of` 与 `find_last_not_of`。对 `"Hello, C++!"` 查找元音集合 `"aeiou"`,首尾命中位置分别为 `1`(`'e'`)和 `4`(`'o'`),首尾非元音位置分别为 `0`(`'H'`)和 `10`(`'!'`)。本站已在离线 G++ C++17 容器实测全部 20 项成员函数。
std::string 常用成员函数汇总表
| 函数名 | 描述 | 示例代码 |
| size() | 返回字符串当前字符数(字节数) | str.size() |
| length() | 与 size() 完全等价,返回字符串长度 | str.length() |
| empty() | 判断字符串是否为空(长度是否为 0) | str.empty() |
| operator[] | 按索引直接访问字符(无边界检查,性能最高) | str[0] |
| at() | 按索引访问字符,越界时抛出 std::out_of_range | str.at(7) |
| substr() | 从指定起始位置截取定长子字符串 | str.substr(7, 5) |
| find() | 从左向右查找子串首次出现位置,未找到返回 npos | str.find("World") |
| rfind() | 从右向左查找子串最后一次出现位置 | str.rfind("l") |
| replace() | 将指定起始位置与长度的子区段替换为新内容 | str.replace(pos, 5, "C++") |
| append() | 在字符串末尾追加字符或子串 | str.append(" How are you?") |
| insert() | 在指定索引位置之前插入内容 | str.insert(7, " Beautiful") |
| erase() | 删除从指定位置开始的若干字符 | str.erase(7, 10) |
| clear() | 清空字符串内容使 size() 归零 | str.clear() |
| c_str() | 返回以 '\0' 结尾的只读 C 风格字符指针 | const char* p = str.c_str(); |
| data() | 返回指向连续字符存储区的指针(C++11+ 同样空终止,C++17 非 const 重载可写) | const char* d = str.data(); |
| compare() | 按字典序比较字符串(相等返回 0,小于返回负,大于返回正) | str.compare("Hello, C++!") |
| find_first_of() | 查找第一个属于给定字符集合中任意字符的索引 | str.find_first_of("aeiou") |
| find_last_of() | 查找最后一个属于给定字符集合中任意字符的索引 | str.find_last_of("aeiou") |
| find_first_not_of() | 查找第一个不属于给定字符集合的字符索引 | str.find_first_not_of("aeiou") |
| find_last_not_of() | 查找最后一个不属于给定字符集合的字符索引 | str.find_last_not_of("aeiou") |
实测 std::string 声明拼接、越界保护 at()、子串查找替换、修改与 C 互操作及字符集搜索
展开查看收起
#include <cstdio>
#include <cstring>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
namespace lab {
struct Case {
std::string name;
std::string expected_json;
std::string actual_json;
bool passed;
};
std::string esc(const std::string& s) {
std::string out = "\"";
for (unsigned char c : s) {
switch (c) {
case '\"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\b': out += "\\b"; break;
case '\f': out += "\\f"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (c < 0x20) {
char buf[8];
std::snprintf(buf, sizeof(buf), "\\u%04x", c);
out += buf;
} else {
out += static_cast<char>(c);
}
}
}
out += "\"";
return out;
}
std::string jbool(bool v) { return v ? "true" : "false"; }
void emit(const std::vector<Case>& cases) {
std::cout << "{\"runtime\": \"G++ C++17 (mstorsjo/llvm-mingw:20260616)\", \"cases\": [";
for (std::size_t i = 0; i < cases.size(); ++i) {
if (i) std::cout << ", ";
std::cout << "{\"name\": " << esc(cases[i].name)
<< ", \"expected\": " << cases[i].expected_json
<< ", \"actual\": " << cases[i].actual_json
<< ", \"passed\": " << jbool(cases[i].passed) << "}";
}
std::cout << "]}\n";
}
} // namespace lab
int main() {
std::vector<lab::Case> cases;
// Case 1: declaration, init, +, size/length/empty, operator[], at()
std::string empty_s;
std::string s1 = "Hello, ";
std::string s2 = "World!";
std::string greeting = s1 + s2;
bool threw_at = false;
try {
(void)greeting.at(99);
} catch (const std::out_of_range&) {
threw_at = true;
}
std::string act1 = "empty=" + std::to_string(empty_s.empty() ? 1 : 0)
+ ";sz=" + std::to_string(greeting.size())
+ ";len=" + std::to_string(greeting.length())
+ ";c0=" + std::string(1, greeting[0])
+ ";c7=" + std::string(1, greeting.at(7))
+ ";oob=" + std::to_string(threw_at ? 1 : 0);
std::string exp1 = "empty=1;sz=13;len=13;c0=H;c7=W;oob=1";
cases.push_back({
"string_init_concat_and_access",
lab::esc(exp1),
lab::esc(act1),
act1 == exp1
});
// Case 2: substr, find, rfind, replace
std::string sub = greeting.substr(7, 5);
std::size_t pos_w = greeting.find("World");
std::size_t rpos_l = greeting.rfind("l");
std::string modified = greeting;
if (pos_w != std::string::npos) {
modified.replace(pos_w, 5, "C++");
}
std::string act2 = "sub=" + sub
+ ";find=" + std::to_string(pos_w)
+ ";rfind=" + std::to_string(rpos_l)
+ ";mod=" + modified;
std::string exp2 = "sub=World;find=7;rfind=10;mod=Hello, C++!";
cases.push_back({
"string_substr_find_replace",
lab::esc(exp2),
lab::esc(act2),
act2 == exp2
});
// Case 3: append, insert, erase, clear, c_str, data, compare
std::string work = modified;
work.append(" How are you?");
work.insert(7, " Beautiful");
std::string after_ins = work;
work.erase(7, 10);
std::string after_era = work;
work.clear();
bool cleared = work.empty();
work = "Hello, C++!";
bool cstr_ok = (std::strcmp(work.c_str(), "Hello, C++!") == 0)
&& (std::memcmp(work.data(), "Hello, C++!", work.size()) == 0)
&& (work.compare("Hello, C++!") == 0)
&& (work.compare("Z") < 0);
std::string act3 = "ins=" + after_ins + "|era=" + after_era
+ "|clr=" + std::to_string(cleared ? 1 : 0)
+ "|cstr=" + std::to_string(cstr_ok ? 1 : 0);
std::string exp3 = "ins=Hello, BeautifulC++! How are you?|era=Hello, C++! How are you?|clr=1|cstr=1";
cases.push_back({
"string_modify_and_c_interop",
lab::esc(exp3),
lab::esc(act3),
act3 == exp3
});
// Case 4: find_first_of, find_last_of, find_first_not_of, find_last_not_of
std::string target = "Hello, C++!";
std::size_t p1 = target.find_first_of("aeiou");
std::size_t p2 = target.find_last_of("aeiou");
std::size_t p3 = target.find_first_not_of("aeiou");
std::size_t p4 = target.find_last_not_of("aeiou");
std::string act4 = std::to_string(p1) + "," + std::to_string(p2) + "," + std::to_string(p3) + "," + std::to_string(p4);
std::string exp4 = "1,4,0,10";
cases.push_back({
"string_char_set_search",
lab::esc(exp4),
lab::esc(act4),
act4 == exp4
});
lab::emit(cases);
return 0;
}
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
`find()` 返回无符号整型 `std::size_t`,无符号数永远大于等于 0;未找到时返回最大无符号值 `std::string::npos`,因此必须写 `pos != std::string::npos`。