【C++笔记】STL详解:string的使用
前言:
本文在介绍STL框架基础上,进一步讲解了迭代器、auto关键字和范围for循环的使用方法,接下来我们将重点探讨string类的常用接口及其应用。
一、string类对象的常见构造
1.1 空字符串构造函数
无参构造函数:string();
函数功能:构造一个空字符串,长度为零字符。
代码示例:演示构造一个空字符
#include <iostream> #include <string> using namespace std; int main() { string s1; // 调用默认构造函数,构造一个空字符串 cout << "s1: " << s1 << endl; // 输出空内容 cout << "s1.size(): " << s1.size() << endl; // 输出 0 return 0; }
打印结果如下所示:

1.2 C 字符串构造函数
构造函数原型: string(const char* s)
函数功能:通过C风格字符串(const char*)构造string 对象
代码示例:演示通过C风格字符串进行构造
#include <iostream> #include <string> using namespace std; int main() { string s2("Hello world"); //通过C类型字符进行构造 cout <<"s2:" << s2 << endl; return 0; }
打印结果如下所示:

1.3 n个字符构造函数
构造函数原型:string(size_t n, char c)
函数功能:用n个字符c进行构造
代码示例:用n个字符‘x’进行构造
#include <iostream> #include <string> using namespace std; int main() { string s3(5,'x'); //通过n个字符进行构造 cout <<"s3:" << s3 << endl; return 0; }
打印结果如下所示:

1.4 拷贝构造函数
构造函数原型: string(const string&s)
函数功能:通过拷贝字符串进行构造
代码示例:调用拷贝构造函数进行构造str对象
#include <iostream> #include <string> using namespace std; int main() { string original = "Hello C++"; string str(original); // 调用拷贝构造函数 cout << "str: " << str << endl; // 输出 "Hello C++" return 0; }
打印结果如下:

二、string类的容量操作
2.1 size
size函数
函数原型: size_t size() const;
函数功能:返回字符串的长度,以字节为单位。
代码示例:演示返回字符串的长度
#include <iostream> #include <string> using namespace std; int main() { string s = "Hello World"; cout << "s.size(): " << s.size() << endl; // 输出 11 return 0; }
打印结果如下所示:

2.2 capacity
capacity函数
函数原型: size_t capacity() const;
函数功能:返回当前为字符串分配的存储空间的大小,以字节为单位。
代码示例:演示返回字符串的空间大小
#include<iostream> #include<string> using namespace std; int main() { string s1("Hello World"); cout <<"s1.capacity():" << s1.capacity() << endl; return 0; }
打印结果如下所示:

2.3 empty
empty函数
函数原型:bool empty() const;
函数功能:检查字符串是否为空。
代码示例:演示字符串是否为空的函数
#include <iostream> #include <string> using namespace std; int main() { string s1 = "hello world"; string s2; cout << "s1.empty(): " << s1.empty() << endl; // 输出 0(false) cout << "s2.empty(): " << s2.empty() << endl; // 输出 1(true) return 0; }
打印结果如下所示:

2.4 clear
clear函数
函数原型:void clear();
函数功能:删除字符串的内容,使其变为一个空字符串(长度为 0 个字符)。
代码示例:清空字符s
#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; // 输出 0 cout << "s.capacity(): " << s.capacity() << endl; // 容量可能不变 return 0; }
打印结果如下图所示:

2.5 reserve
reserve 函数
函数原型: void reserve (size_t n = 0);
函数功能: 请求将字符串容量调整为计划中的大小变化,最多为 n 个字符。
①如果 n 大于当前字符串容量,该函数将使容器将其容量增加到 n 个字符(或更多)。
②在其他所有情况下,它被视为一个非约束性的请求来缩小字符串容量:容器实现可以自由优化,并保留字符串的容量大于 n。
注:不同编译器(如 GCC, Clang, MSVC)的初始容量和扩容策略可能略有不同,但核心逻辑一致。
代码示例演示:展示扩容函数的使用
#include <iostream> #include <string> using namespace std; // 引入标准命名空间 int main() { string str1; string str2; cout << "=== 不使用 reserve ===" << endl; cout << "初始 str1 容量: " << str1.capacity() << ", 长度: " << str1.length() << endl; // 假设我们要存入一段较长的文本 str1 = "This is a demonstration of the string reserve function in C++."; cout << "赋值后 str1 容量: " << str1.capacity() << ", 长度: " << str1.length() << endl; cout << "\n=== 使用 reserve ===" << endl; cout << "初始 str2 容量: " << str2.capacity() << ", 长度: " << str2.length() << endl; // 预先分配至少 100 个字符的内存 str2.reserve(100); cout << "reserve(100) 后,str2 容量: " << str2.capacity() << ", 长度: " << str2.length() << endl; // 存入同样的文本 str2 = "This is a demonstration of the string reserve function in C++."; cout << "赋值后 str2 容量: " << str2.capacity() << ", 长度: " << str2.length() << endl; return 0; }
打印结果如下图所示:

2.6 resize
resize函数
函数原型:
①void resize (size_t n);
②void resize (size_t n, char c);
函数功能:将字符串调整为 n 个字符的长度。
A.如果 n 小于当前字符串长度,当前值将被缩短到其前 n 个字符,删除第 n 个字符之后的部分。
B.如果 n 大于当前字符串长度,当前内容将被扩展,在末尾插入所需数量的字符以达到 n 的长度。如果指定了 c,新元素将被初始化为 c 的副本,否则,它们将被值初始化的字符(空字符)。
代码演示:resize的功能
#include <iostream> #include <string> using namespace std; int main() { string s = "Hello C"; s.resize(9, '+'); // 扩展至9个字符,不足部分用'+'填充 cout << "s: " << s << endl; // 输出 "Helloxxx" cout << "s.size():" << s.size() << endl; s.resize(5); // 截断至5字符 cout << "s: " << s << endl; // 输出 "Hello" cout << "s.size(): " << s.size() << endl; return 0; }
打印结果如下图所示:

三、 string类的访问及遍历操作
3.1 operator[]
操作符重载 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"); //1. 下标+[] 进行访问元素 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();
函数功能:
① iterator begin(): 返回一个指向字符串第一个字符的迭代器。
② iterator 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循环
代码示例:通过范围for进行遍历字符串
#include <iostream> #include <string> using namespace std; int main() { string s2("hello world"); //范围for的使用场景主要应用于: 容器 和 数组 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
push_back 函数
函数原型:void push_back (char c);
函数功能 :将字符 c 附加到字符串末尾,使其长度增加一个。
代码示例:演示向字符串中尾插单个字符
#include <iostream> #include <string> using namespace std; int main() { string s("hello world"); cout << "尾插前的s:" << s << endl; // push_back 函数只能尾插单个字符 s.push_back(' '); s.push_back('s'); cout << "push_back尾插字符后的s:" << s << endl; return 0; }
打印结果如下所示:

4.2 operator+= 和 append
1. +=操作符重载(常用)
函数原型:
① string& operator+= (const string& str);
② string& operator+= (const char* s);
③ string& operator+= (char c);
函数功能:通过在当前值的末尾追加额外的字符来扩展字符串:
代码示例:演示+=运算符重载,尾插单个字符,C类型字符串,string类型字符串
#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);
函数功能:通过在当前值的末尾追加附加字符来扩展字符串。
代码示例:通过append函数扩展字符串
#include <iostream> #include <string> using namespace std; int main() { string s("Hello world"); cout << "尾插前的s:" << s << endl; //append 函数尾插字符串 s.append(" Welcome C++"); cout << "append尾插字符串后的s:" << s << endl; return 0; }

4.3 c_str
c_str 函数
函数原型: const char* c_str() const;
函数功能: 返回一个指向包含空字符终止序列的字符数组(即 C 字符串)的指针,该数组表示字符串对象的当前值。
代码示例:获取C风格字符串
#include <iostream> #include <string> #include <cstring> using namespace std; int main() { string s = "C++"; const char* p = s.c_str(); // 获取C风格字符串指针 cout << "C-string: " << p << endl; // 输出 "C++" cout << "Length via strlen: " << strlen(p) << endl; // 输出 3 return 0; }
打印结果如下所示:

4.4 find
find函数
函数原型:
① size_t find (const string& str, size_t pos = 0) const;
②size_t find (char c, size_t pos = 0) const;
函数功能:
① 从pos位置(默认为0) 查找一个字符串
②从pos位置(默认为0) 查找一个字符
注意:如果没有找到匹配项,该函数返回 string::npos,npos的类型是size_t,其值被认定为是-1。
代码示例:演示查找单个字符和单个字符串,以及验证未查找到字符串返回值
#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
substr函数
函数原型:string substr (size_t pos = 0, size_t len = npos) const;
函数功能:返回一个新构建的string对象,其值初始化为对此对象的一个子字符串的副本。
代码示例:演示截取字符串
#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); // "think" cout << "截取得到下标从3开始之后的五个字符:" << str2 << endl; size_t pos = str.find("live"); // position of "live" in str string str3 = str.substr(pos); // get from "live" to the end cout <<"截取pos位置之后的字符串:" << str3 << '\n'; return 0; }
打印结果如下所示:

4.6 insert
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; // insert函数 插入C类型字符串 s.insert(0, " Byte "); cout << "insert在下标0处插入字符串后的s:" << s << endl; //insert函数 插入string类型字符串 string s2(" Welcome to C++"); size_t pos = s.size(); s.insert(pos, s2); cout << "insert在下标pos处插入字符串后的s:" << s<< endl; //insert插入单个字符需要指定字符个数 s.insert(0, 5, '6'); cout << "insert在下标0处插入5个字符串后的s:" << s << endl; return 0; }
打印结果如下所示:

4.7 erase
erase函数
函数原型:string& erase (size_t pos = 0, size_t len = npos);
函数功能:删除字符串的一部分,缩短其长度:
代码示例:
#include <iostream> #include <string> using namespace std; // 引入标准命名空间 int main() { string str("This is an example sentence."); cout << str << '\n'; // 初始输出: "This is an example sentence." // 用法 :erase(pos, len) // 从索引 10 开始,删除 8 个字符 (" example") str.erase(10, 8); cout << str << '\n'; // 当前结果: "This is an sentence." return 0; }
打印结果如下所示:

五、string类的非成员函数
5.1 operator+
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);
函数功能:返回一个新构造的字符串对象,其值为 lhs 中的字符后跟 rhs 中的字符的组合。
代码示例:
#include <iostream> #include <string> using namespace std; int main() { string firstlevel("com"); string secondlevel("cplusplus"); string scheme("http://"); string hostname; string url; // 演示 1:string 与 C风格字符串 ("www.")、字符 ('.') 以及其它 string 拼接 hostname = "www." + secondlevel + '.' + firstlevel; // 演示 2:两个 string 对象直接拼接 url = scheme + hostname; cout << url << '\n'; // 预期输出: http://www.cplusplus.com return 0; }
打印结果如下所示:

5.2 operator>> 和 operator<<
operator>> 和 operator<<(输入/输出运算符重载)
函数原型:
① istream& operator>> (istream& is, string& str);
② ostream& operator<< (ostream& os, const string& str);
函数功能:
A. operator>> :从流中读取数据到 string,默认以空格/换行分隔
B. 将符合 str 值的字符序列插入到 os 中。
代码示例:
#include <iostream> #include <string> using namespace std; int main() { string s; // 输入示例(遇到空格/换行停止) cout << "Enter a word: "; cin >> s; // 输入 "Hello World" cout << "You entered: " << s << endl; // 输出 "Hello"(空格截断) // 输出示例 string name = "Alice"; cout << "Name: " << name << endl; // 输出 "Name: Alice" return 0; }
5.3 getline
getline函数
函数原型:
①istream& getline (istream& is, string& str, char delim);
②istream& getline (istream& is, string& str);
函数功能:从输入流中读取一行(默认以 \n 结尾),可指定分隔符,不会因为' '而中断。
代码示例:
#include <iostream> #include <string> using namespace std; int main() { string line; cout << "Enter a line: "; getline(cin, line); // 读取整行(包括空格) cout << "Line: " << line << endl; // 输出完整输入 // 指定分隔符(默认'\n') 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; }
打印结果如下所示:

既然看到这里了,不妨关注+点赞+收藏,感谢大家,若有问题请指正。
