跳到主要内容C++ string 类详解:初始化、遍历与常用函数 | 极客日志C++算法
C++ string 类详解:初始化、遍历与常用函数
C++ string 类是处理文本的核心工具。本文涵盖初始化方式(默认、直接构造、拷贝)、三种遍历方法(下标、范围 for、迭代器)及容量管理(size 与 capacity 区别)。重点解析常用成员函数如 append、substr、find 和 replace,并指出 cin 与 getline 混用的常见陷阱。通过实际代码示例展示内存分配机制与字符串操作细节,帮助开发者高效掌握标准库用法。
魔法巫师0 浏览 一、string 的初始化与遍历
在使用 std::string 之前,记得包含 <string> 头文件。它支持 cin 输入和 cout 输出,是处理文本的核心工具。
1. string 的初始化
这里主要介绍三种最常用的初始化方式。
默认初始化
创建一个空字符串。
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1;
cout << s1 << endl;
return 0;
}
直接构造
显式调用构造函数,传入 C 风格字符串。
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1("Hello world");
cout << s1 << endl;
return 0;
}
拷贝构造
利用已有的 string 对象创建一个副本。
#include <iostream>
#include <string>
using namespace std;
int main {
string s1;
cin >> s1;
;
cout << s2 << endl;
;
}
()
string s2(s1)
return
0
2. string 的遍历
2.1 下标访问
size() 和 length() 都返回字符个数(字节数,不含末尾隐藏的 \0)。早期 length() 独立存在,后来为了符合 STL 容器统一接口规范增加了 size(),建议优先使用 size()。
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1("HelloWorld");
cout << s1.size() << endl;
cout << s1.length() << endl;
return 0;
}
operator[] 重载了方括号运算符,用于读取或修改字符。注意越界访问可能导致未定义行为或读取垃圾数据。
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1("HelloWorld");
cout << s1[5] << endl;
s1[6] = 'M';
cout << s1 << endl;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1("HelloWorld");
for (int i = 0; i < s1.size(); i++) {
cout << s1[i] << " ";
}
cout << endl;
return 0;
}
2.2 范围 for 循环
C++11 引入的范围 for 循环简化了遍历过程,底层通常替换为迭代器实现。
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1("HelloWorld");
for (auto e : s1) {
cout << e << " ";
}
cout << endl;
return 0;
}
注意: 如果直接使用 auto e,变量是值拷贝,修改 e 不会影响原字符串。若需修改,应使用引用 auto &e。
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1("HelloWorld");
for (auto &e : s1) {
e = 'm';
cout << e << " ";
}
cout << endl;
cout << s1 << endl;
return 0;
}
2.3 迭代器遍历
迭代器充当通用指针,屏蔽底层实现细节。begin() 指向首元素,end() 指向尾元素之后。
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1("HelloWorld");
string::iterator it = s1.begin();
while (it != s1.end()) {
cout << *it << " ";
it++;
}
cout << endl;
return 0;
}
反向迭代器 rbegin() 和 rend() 可用于倒序遍历。
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1("HelloWorld");
string::reverse_iterator it = s1.rbegin();
while (it != s1.rend()) {
cout << *it << " ";
it++;
}
cout << endl;
return 0;
}
二、有关 string 容量的函数
string 底层由指针、大小(Size)、容量(Capacity)及内部缓冲区组成。Size 记录有效字符数,Capacity 记录分配总空间。
1. capacity
容量不一定等于 Size,额外空间允许添加新字符而不必立即重新分配内存。不同编译器扩容策略可能不同(如 VS 默认先开 16 字节缓冲,超出后按倍数增长)。
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1("HelloWorld");
size_t sz = s1.capacity();
cout << "capacity changed: " << sz << '\n';
cout << "making s grow:\n";
for (int i = 0; i < 100; ++i) {
s1.push_back('c');
if (sz != s1.capacity()) {
sz = s1.capacity();
cout << "capacity changed: " << sz << '\n';
}
}
cout << endl;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1("HelloWorld");
s1.reserve(100);
cout << s1.capacity() << endl;
return 0;
}
2. 其它容量相关函数
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1("HelloWorld");
s1.clear();
cout << s1.size() << endl;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1("HelloWorld");
s1.clear();
if (s1.empty()) {
cout << "字符串为空" << endl;
}
return 0;
}
三、常用的成员函数
1. operator+=
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1("HelloWorld");
cout << s1 << endl;
s1 += " Hello kong";
cout << s1 << endl;
return 0;
}
2. push_back
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1("HelloWorld");
cout << s1 << endl;
s1.push_back(' ');
s1.push_back('m');
cout << s1 << endl;
return 0;
}
3. append
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1("HelloWorld");
s1.append("geerghre");
cout << s1 << endl;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1 = "I love ";
string s2 = "C++ Programming";
s1.append(s2, 4, 7);
cout << s1 << endl;
return 0;
}
4. substr
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1("HelloWorld");
string s2 = s1.substr(5);
cout << s2 << endl;
return 0;
}
5. find 与 replace
find:搜索首次出现位置,未找到返回 npos。
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1("HelloWorld");
size_t pos = s1.find('#');
if (pos == string::npos) {
cout << "没有这个字符串" << endl;
}
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1("Hello.Worl.dtdjd.dhsdjt");
size_t pos = s1.find('.');
while (pos != string::npos) {
s1.replace(pos, 1, "##");
pos = s1.find('.', pos + 2);
}
cout << s1 << endl;
return 0;
}
6. getline
处理含空格的整行输入。注意混用 cin >> 时残留换行符的问题。
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1, s2;
cout << "请输入 s1 的字符串:";
cin >> s1;
cout << "s1 的字符串为:" << s1 << endl << endl;
cin.ignore();
cout << "请输入 s2 的字符串:";
getline(cin, s2);
cout << "s2 的字符串为:" << s2 << endl;
return 0;
}
相关免费在线工具
- 加密/解密文本
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
- Gemini 图片去水印
基于开源反向 Alpha 混合算法去除 Gemini/Nano Banana 图片水印,支持批量处理与下载。 在线工具,Gemini 图片去水印在线工具,online
- Base64 字符串编码/解码
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
- Base64 文件转换器
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
- Markdown转HTML
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online
- HTML转Markdown
将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML转Markdown在线工具,online