跳到主要内容
C++ STL string 类详解与实战 | 极客日志
C++ 算法
C++ STL string 类详解与实战 综述由AI生成 C++ STL string 类封装了底层内存管理,提供便捷的字符串操作接口。内容涵盖对象构造、容量控制、字符访问、内容修改及非成员函数五大模块。重点解析了 reserve 预分配、resize 调整大小、find 查找定位、substr 截取子串等常用方法,并通过 += 与 append 的对比展示性能差异。配合迭代器与范围 for 循环示例,帮助开发者深入理解 string 内部机制与最佳实践。
怪力乱神 发布于 2026/3/23 更新于 2026/4/26 2 浏览前言
在 STL 框架下,string 类是处理文本数据的核心工具。本文将结合迭代器、auto 关键字和范围 for 循环,深入探讨 string 类的常用接口及其应用细节。
一、string 类对象的常见构造
1.1 空字符串构造函数
无参构造函数: string();
作用: 构造一个长度为 0 的空字符串。
#include <iostream>
#include <string>
using namespace std;
int main () {
string s1;
cout << "s1: " << s1 << endl;
cout << "s1.size(): " << s1. size () << endl;
return 0 ;
}
预期输出为空行及 0。
1.2 C 字符串构造函数
原型: string(const char* s);
作用: 通过 C 风格字符串(const char*)初始化 string 对象。
#include <iostream>
#include <string>
using namespace std;
int main () {
string s2 ("Hello world" ) ;
cout << "s2: " << s2 << endl;
return 0 ;
}
预期输出 Hello world。
1.3 n 个字符构造函数
原型: string(size_t n, char c);
作用: 用 n 个字符 c 进行构造。
#include <iostream>
#include <string>
using namespace std;
int main () {
string s3 (5 , 'x' ) ;
cout << "s3: " << s3 << endl;
return 0 ;
}
1.4 拷贝构造函数 原型: string(const string& s);
作用: 通过拷贝另一个 string 对象进行构造。
#include <iostream>
#include <string>
using namespace std;
int main () {
string original = "Hello C++" ;
string str (original) ;
cout << "str: " << str << endl;
return 0 ;
}
二、string 类的容量操作
2.1 size 原型: size_t size() const;
作用: 返回字符串的实际长度(字节数)。
#include <iostream>
#include <string>
using namespace std;
int main () {
string s = "Hello World" ;
cout << "s.size(): " << s.size () << endl;
return 0 ;
}
2.2 capacity 原型: size_t capacity() const;
作用: 返回当前分配的存储空间大小(字节数),通常大于等于 size。
#include <iostream>
#include <string>
using namespace std;
int main () {
string s1 ("Hello World" ) ;
cout << "s1.capacity(): " << s1. capacity () << endl;
return 0 ;
}
2.3 empty 原型: bool empty() const;
作用: 检查字符串是否为空(size 为 0)。
#include <iostream>
#include <string>
using namespace std;
int main () {
string s1 = "hello world" ;
string s2;
cout << "s1.empty(): " << s1. empty () << endl;
cout << "s2.empty(): " << s2. empty () << endl;
return 0 ;
}
2.4 clear 原型: void clear();
作用: 删除内容,使字符串变为空(size 为 0),但可能保留 capacity。
#include <iostream>
#include <string>
using namespace std;
int main () {
string s = "Hello World" ;
s.clear ();
cout << "After clear, s: " << s << endl;
cout << "s.size(): " << s.size () << endl;
cout << "s.capacity(): " << s.capacity () << endl;
return 0 ;
}
2.5 reserve 原型: void reserve(size_t n = 0);
作用: 请求将容量调整为至少 n。若 n 大于当前容量,则扩容;否则视为优化建议,具体实现由编译器决定。注意不同编译器策略可能略有差异。
#include <iostream>
#include <string>
using namespace std;
int main () {
string str1, str2;
cout << "=== 不使用 reserve ===" << endl;
cout << "初始 str1 容量:" << str1. capacity () << ", 长度:" << str1.l ength() << endl;
str1 = "This is a demonstration of the string reserve function in C++." ;
cout << "赋值后 str1 容量:" << str1. capacity () << ", 长度:" << str1.l ength() << endl;
cout << "\n=== 使用 reserve ===" << endl;
cout << "初始 str2 容量:" << str2. capacity () << ", 长度:" << str2.l ength() << endl;
str2. reserve (100 );
cout << "reserve(100) 后,str2 容量:" << str2. capacity () << ", 长度:" << str2.l ength() << endl;
str2 = "This is a demonstration of the string reserve function in C++." ;
cout << "赋值后 str2 容量:" << str2. capacity () << ", 长度:" << str2.l ength() << endl;
return 0 ;
}
2.6 resize
void resize(size_t n);
void resize(size_t n, char c);
作用: 调整字符串长度为 n。若缩短则截断;若增长则填充(可指定字符 c,默认为空字符)。
#include <iostream>
#include <string>
using namespace std;
int main () {
string s = "Hello C" ;
s.resize (9 , '+' );
cout << "s: " << s << endl;
cout << "s.size(): " << s.size () << endl;
s.resize (5 );
cout << "s: " << s << endl;
cout << "s.size(): " << s.size () << endl;
return 0 ;
}
三、string 类的访问及遍历操作
3.1 operator[]
char& operator[](size_t pos);
const char& operator[](size_t pos) const;
作用: 返回位置 pos 处字符的引用,支持读写。
#include <iostream>
#include <string>
using namespace std;
int main () {
string s2 ("hello world" ) ;
cout << "下标访问元素:" ;
for (int i = 0 ; i < s2. size (); i++) {
cout << s2[i] << " " ;
}
s2[0 ] = 'H' ;
cout << "\n更改后下标位置 2 处的字符串:" ;
for (int i = 0 ; i < s2. size (); i++) {
cout << s2[i] << " " ;
}
return 0 ;
}
3.2 迭代器获取:begin 和 end
iterator begin();
iterator end();
作用: begin 指向首字符,end 指向末尾之后。
#include <iostream>
#include <string>
using namespace std;
int main () {
string s2 ("hello world" ) ;
cout << "迭代器访问元素:" ;
string::iterator it = s2. begin ();
while (it != s2. end ()) {
cout << *it << " " ;
++it;
}
cout << "\n利用迭代器更改元素:" ;
it = s2. begin ();
while (it != s2. end ()) {
*it += 2 ;
cout << *it << " " ;
++it;
}
return 0 ;
}
3.3 范围 for 循环 #include <iostream>
#include <string>
using namespace std;
int main () {
string s2 ("hello world" ) ;
cout << "范围 for 循环访问元素:" ;
for (auto & ch : s2) {
cout << ch << " " ;
}
cout << "\n范围 for 循环更改元素:" ;
for (auto & ch : s2) {
ch += 2 ;
cout << ch << " " ;
}
return 0 ;
}
四、string 类的修改操作
4.1 push_back 原型: void push_back(char c);
作用: 在字符串末尾追加单个字符。
#include <iostream>
#include <string>
using namespace std;
int main () {
string s ("hello world" ) ;
cout << "尾插前的 s:" << s << endl;
s.push_back (' ' );
s.push_back ('s' );
cout << "push_back 尾插字符后的 s:" << s << endl;
return 0 ;
}
4.2 operator+= 和 append
string& operator+=(const string& str);
string& operator+=(const char* s);
string& operator+=(char c);
作用: 扩展字符串。
#include <iostream>
#include <string>
using namespace std;
int main () {
string s ("hello world" ) ;
cout << "尾插前的 s:" << s << endl;
s += 'x' ;
cout << "尾插单个字符的 s:" << s << endl;
s += " Welcome" ;
cout << "尾插 C 类型字符串后的 s:" << s << endl;
string s2 (" Hello C++" ) ;
s += s2;
cout << "尾插字符串 s2 后的 s:" << s << endl;
return 0 ;
}
2. append 函数
原型: string& append(const string& str);
作用: 追加字符串,功能类似 +=。
#include <iostream>
#include <string>
using namespace std;
int main () {
string s ("Hello world" ) ;
cout << "尾插前的 s:" << s << endl;
s.append (" Welcome C++" );
cout << "append 尾插字符串后的 s:" << s << endl;
return 0 ;
}
4.3 c_str 原型: const char* c_str() const;
作用: 返回指向 C 风格字符串(以 null 结尾)的指针。
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main () {
string s = "C++" ;
const char * p = s.c_str ();
cout << "C-string: " << p << endl;
cout << "Length via strlen: " << strlen (p) << endl;
return 0 ;
}
4.4 find
size_t find(const string& str, size_t pos = 0) const;
size_t find(char c, size_t pos = 0) const;
作用: 从 pos 位置查找字符串或字符。未找到返回 string::npos。
#include <iostream>
#include <string>
using namespace std;
int main () {
string s ("text.cpp.zip" ) ;
size_t pos1 = s.find ('.' );
cout << "字符串 s 中 . 的位置为:" << pos1 << endl;
size_t pos2 = s.find ("cpp" );
cout << "字符串 s 中 cpp 的位置为:" << pos2 << endl;
size_t pos3 = s.find ("C++" );
if (pos3 == string::npos) {
cout << "Not find!" <<endl;
}
return 0 ;
}
4.5 substr 原型: string substr(size_t pos = 0, size_t len = npos) const;
作用: 返回从 pos 开始长度为 len 的子字符串副本。
#include <iostream>
#include <string>
using namespace std;
int main () {
string str = "We think in generalities, but we live in details." ;
string str2 = str.substr (3 , 5 );
cout << "截取得到下标从 3 开始之后的五个字符:" << str2 << endl;
size_t pos = str.find ("live" );
string str3 = str.substr (pos);
cout << "截取 pos 位置之后的字符串:" << str3 << '\n' ;
return 0 ;
}
4.6 insert
string& insert(size_t pos, const string& str);
string& insert(size_t pos, const char* s);
string& insert(size_t pos, size_t n, char c);
作用: 在 pos 位置插入额外字符。
#include <iostream>
#include <string>
using namespace std;
int main () {
string s ("hello world" ) ;
cout << "尾插前的 s:" << s << endl;
s.insert (0 , " Byte " );
cout << "insert 在下标 0 处插入字符串后的 s:" << s << endl;
string s2 (" Welcome to C++" ) ;
size_t pos = s.size ();
s.insert (pos, s2);
cout << "insert 在下标 pos 处插入字符串后的 s:" << s << endl;
s.insert (0 , 5 , '6' );
cout << "insert 在下标 0 处插入 5 个字符串后的 s:" << s << endl;
return 0 ;
}
4.7 erase 原型: string& erase(size_t pos = 0, size_t len = npos);
作用: 删除从 pos 开始的 len 个字符。
#include <iostream>
#include <string>
using namespace std;
int main () {
string str ("This is an example sentence." ) ;
cout << str << '\n' ;
str.erase (10 , 8 );
cout << str << '\n' ;
return 0 ;
}
五、string 类的非成员函数
5.1 operator+
string operator+(const string& lhs, const string& rhs);
string operator+(const string& lhs, const char* rhs);
string operator+(const char* lhs, const string& rhs);
作用: 返回新构造的拼接字符串。
#include <iostream>
#include <string>
using namespace std;
int main () {
string firstlevel ("com" ) ;
string secondlevel ("cplusplus" ) ;
string scheme ("http://" ) ;
string hostname;
string url;
hostname = "www." + secondlevel + '.' + firstlevel;
url = scheme + hostname;
cout << url << '\n' ;
return 0 ;
}
5.2 operator>> 和 operator<<
istream& operator>>(istream& is, string& str);
ostream& operator<<(ostream& os, const string& str);
作用: 输入流读取(遇空格停止),输出流写入。
#include <iostream>
#include <string>
using namespace std;
int main () {
string s;
cout << "Enter a word: " ;
cin >> s;
cout << "You entered: " << s << endl;
string name = "Alice" ;
cout << "Name: " << name << endl;
return 0 ;
}
5.3 getline
istream& getline(istream& is, string& str, char delim);
istream& getline(istream& is, string& str);
作用: 读取整行(包括空格),直到遇到分隔符或换行。
#include <iostream>
#include <string>
using namespace std;
int main () {
string line;
cout << "Enter a line: " ;
getline (cin, line);
cout << "Line: " << line << endl;
getline (cin, line, ';' );
cout << "Until ';': " << line << endl;
return 0 ;
}
5.4 字符串大小比较 #include <iostream>
#include <string>
using namespace std;
int main () {
string foo = "alpha" ;
string bar = "beta" ;
if (foo == bar) cout << "foo and bar are equal\n" ;
if (foo != bar) cout << "foo and bar are not equal\n" ;
if (foo < bar) cout << "foo is less than bar\n" ;
if (foo > bar) cout << "foo is greater than bar\n" ;
if (foo <= bar) cout << "foo is less than or equal to bar\n" ;
if (foo >= bar) cout << "foo is greater than or equal to bar\n" ;
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