C++ string操作指南:从入门到精通

张开发
2026/4/18 15:37:07 15 分钟阅读

分享文章

C++ string操作指南:从入门到精通
一、为什么要用 string之前学的char[]缺点必须手动处理\0容易乱码不能直接用赋值、拼接长度受限容易越界函数少操作麻烦string 优点是 C 标准类安全方便可以直接、、比较自动管理内存不用管\0内置大量常用函数头文件#include string using namespace std;二、string 定义与初始化// 1. 空字符串 string s1; // 2. 直接初始化 string s2 hello world; // 3. 构造方式 string s3(C string); // 4. 重复 n 个字符 string s4(5, a); // aaaaa三、最常用操作必背1. 赋值 string s; s hello;2. 拼接 string s1 hello; string s2 world; string s3 s1 s2; // hello world3. 访问单个字符像数组一样string s hello; cout s[0]; // h cout s[1]; // e4. 比较 !直接按字典序比较非常方便string s1 apple; string s2 banana; if (s1 s2) { … } // 成立 if (s1 apple) { … }四、string 常用成员函数1. 获取长度int len s.size(); // 常用 int len s.length(); // 一样2. 判断是否为空if (s.empty()) { … }3. 截取子串 substr// 从下标 0 开始取 3 个字符 string sub s.substr(0, 3);4. 查找 find查找失败返回 string::nposint pos s.find(llo); if (pos ! string::npos) { cout 找到了下标 pos; }5. 替换 replace// 从下标 2 开始删除 2 个字符替换成 xx s.replace(2, 2, xx);6. 插入 inserts.insert(1, ); // 下标 1 处插入7. 删除 erases.erase(2, 3); // 从下标 2 删 3 个字符五、输入与输出string s; cin s; // 遇到空格/回车停止 getline(cin, s); // 读取一整行包括空格 cout s endl;注意cin s后如果要用getline需要吸收换行符。六、完整综合示例#include iostream #include string using namespace std; int main() { string s hello c; cout 长度 s.size() endl; cout 子串 s.substr(0, 5) endl; int pos s.find(c); if (pos ! string::npos) { cout c 在下标 pos endl; } s.replace(6, 3, Python); cout 替换后 s endl; system(pause); return 0; }七、string vs char [] 对比面试常问表格特性char[]string内存固定大小手动管理自动扩容赋值 / 拼接不能直接可以直接用结束符必须\0自动处理安全性易越界、乱码更安全功能极少非常丰富一句话C 写字符串优先用 string八、新手易错点忘记#include string用scanf/printf直接读写 string会错find没找到不判断直接用下标下标越界访问混用cin 和getline导致读空行九、今日重点总结string是 C 标准字符串头文件string支持直接赋值、拼接、比较常用函数size() / empty() / substr() / find() / replace() / insert() / erase()读整行用getline(cin, s)比 char 数组更安全、更强大优先使用

更多文章