`std::string` 是 C++ 标准模板库(STL)中的一个非常重要的类,用于处理文本字符串。它是 `std::basic_string` 的 typedef,定义在头文件 `` 中。 下面我为你系统总结 `std::string` 的所有常用用法和函数,按类别分类,力求全面: --- ### 🔹 1. **构造函数** ```cpp std::string s1; // 空字符串 std::string s2("hello"); // 从 C 字符串构造 std::string s3(s2); // 拷贝构造 std::string s4(s2, 1, 3); // 从 s2 的第1个字符起拷贝3个字符 -> "ell" std::string s5(5, 'x'); // 重复字符 -> "xxxxx" std::string s6 = {'a','b','c'}; // 用 initializer_list ``` --- ### 🔹 2. **赋值和操作符** ```cpp s1 = "world"; s2 = s1; s3 = std::move(s1); // 移动赋值 s1 += "!"; // 拼接 std::string s = s2 + s3; ``` --- ### 🔹 3. **基本成员函数** ```cpp s.size(); // 返回长度 s.length(); // 同 size() s.empty(); // 是否为空 s.clear(); // 清空 s.capacity(); // 当前容量 s.reserve(100); // 预留容量 s.shrink_to_fit(); // 收缩容量 ``` --- ### 🔹 4. **访问字符** ```cpp s[i]; // 下标访问(不检查越界) s.at(i); // 带越界检查 s.front(); // 第一个字符 s.back(); // 最后一个字符 ``` --- ### 🔹 5. **修改字符串** ```cpp s.insert(pos, "abc"); // 插入字符串 s.insert(pos, 5, 'x'); // 插入5个x s.erase(pos, len); // 删除从 pos 起 len 个字符 s.replace(pos, len, "newstr"); // 替换部分内容 s.push_back('c'); // 追加一个字符 s.pop_back(); // 移除最后一个字符 s.append("extra"); // 追加字符串 s.swap(s2); // 交换两个字符串 ``` --- ### 🔹 6. **查找字符串** ```cpp s.find("abc"); // 查找子串,返回位置或 string::npos s.find("abc", pos); // 从指定位置起查找 s.rfind("abc"); // 反向查找 s.find_first_of("abc"); // 查找任一字符 s.find_last_of("abc"); // 查找任一字符(从后往前) s.find_first_not_of(" \n"); // 找第一个不是空格或换行的字符 ``` --- ### 🔹 7. **子串** ```cpp s.substr(pos); // 从 pos 到末尾的子串 s.substr(pos, len); // 从 pos 起 len 个字符 ``` --- ### 🔹 8. **比较字符串** ```cpp s1 == s2; s1 != s2; s1 < s2; s1.compare(s2); // 返回 <0, =0, >0 s1.compare(pos, len, s2); ``` --- ### 🔹 9. **C 风格字符串** ```cpp s.c_str(); // 返回 const char* 指针 s.data(); // 类似 c_str(),但 C++17 起返回非 null 终止的指针 ``` --- ### 🔹 10. **迭代器** ```cpp s.begin(); s.end(); // 正向迭代器 s.rbegin(); s.rend(); // 反向迭代器 const_iterator it = s.cbegin(); // 常量迭代器 ``` --- ### 🔹 11. **输入输出** ```cpp std::cin >> s; // 读入单词 std::getline(std::cin, s); // 读入整行(包含空格) std::cout << s; // 输出字符串 ``` --- ### 🔹 12. **其他函数** ```cpp s.resize(10); // 改变字符串长度 s.resize(10, 'x'); // 用'x'填充 std::hash{}(s); // 获取哈希值 ``` --- ### 🔹 13. **C++20 增强** 在 C++20 中,`std::string` 支持了 Ranges、`starts_with()`、`ends_with()` 等: ```cpp s.starts_with("http"); // 是否以 http 开头 s.ends_with(".com"); // 是否以 .com 结尾 ``` --- ### 🔹 14. **和 C 字符串兼容** ```cpp const char* cstr = s.c_str(); // 可用于 C 函数如 printf("%s", s.c_str()) std::string(some_c_str); // 从 C 字符串构造 ``` --- ### 🔹 15. **字符串与数字转换** ```cpp int i = std::stoi("123"); double d = std::stod("3.14"); std::string s = std::to_string(42); ``` --- 如需我帮你整理成一份笔记或 Markdown 文件,也可以告诉我!你也可以提你最常用的用法,我帮你列举示例。