
| 🔭 个人主页:散峰而望 |
|---|
《C语言:从基础到进阶》《编程工具的下载和使用》《C语言刷题》
《C++》《算法竞赛从入门到获奖》《人工智能》《AI Agent》
🎬博主简介



【C++】string 类深度剖析:常用接口和编译器差异一网打尽
前言
在C++编程中,字符串处理是极为常见的需求。传统C风格字符串(字符数组)因其繁琐的内存管理和功能限制,逐渐被更高效、更安全的std::string类取代。作为STL(标准模板库)的核心组件之一,string类不仅封装了动态字符序列的操作,还提供了丰富的接口和优化的性能。
本文将从STL的基础概念切入,逐步深入剖析string类的设计原理、常用接口及底层实现细节。内容涵盖构造与遍历、容量管理、修改操作等核心功能,并对比不同编译器(如GCC、MSVC)下的实现差异,帮助开发者彻底掌握string类的应用与优化技巧。
无论你是初学者还是经验丰富的程序员,理解string类的底层机制将显著提升代码的健壮性和效率。通过本文的学习,你将能够:
- 熟练使用
string类解决实际问题; - 避免常见的内存与性能陷阱;
- 深入理解STL容器的设计哲学。
1. STL
1.1 什么是 STL
STL(Standard Template Library,标准模板库)是 C++ 标准库的核心组成部分。它不仅是一个可复用的组件库,更是一个囊括了多种数据结构和通用算法的软件框架,能够显著提升 C++ 程序的开发效率与代码质量。
1.2 STL 的主要版本
STL 在发展过程中产生了多个重要版本,各具特点:
- HP 版本(原始版本)
由 Alexander Stepanov 和 Meng Lee 在惠普实验室完成,是所有 STL 实现的始祖。该版本遵循开源精神,允许任何人任意使用、拷贝、修改、传播甚至商业使用,唯一要求是衍生品必须同样开源。
- P. J. 版本
由 P. J. Plauger 开发,继承自 HP 版本。被微软 Visual C++ 采用,不可公开或修改。缺点是代码可读性较低,符号命名较为怪异。
- RW 版本
由 Rouge Wage 公司开发,继承自 HP 版本。被 C++ Builder 采用,不可公开或修改,可读性一般。
- SGI 版本
由 Silicon Graphics Computer Systems, Inc. 开发,继承自 HP 版本。被 GCC(Linux 环境下的主流编译器)采用,可移植性好,允许公开、修改甚至销售。其命名与编程风格一致,可读性非常高。我们在后续学习 STL 并阅读源代码时,主要参考的就是 SGI 版本。
1.3 STL 的六大件

1.4 STL 的重要性
STL(Standard Template Library,标准模板库)是 C++ 标准库的核心组成部分,提供了大量可复用的通用数据结构和算法。其重要性体现在以下几个方面:
提高开发效率
STL 封装了常用的数据结构(如向量、链表、队列)和算法(如排序、查找),开发者无需重复实现这些基础功能,可直接调用现成组件,显著减少编码工作量。
保证代码质量
STL 经过严格测试和优化,其实现通常比手动编写的代码更高效、更健壮。例如,std::sort 在大多数场景下优于自定义的快速排序实现。
泛型编程支持
STL 基于模板设计,支持泛型编程。同一套算法可以适配不同类型的数据结构,例如std::find 既可用于数组,也可用于链表,增强了代码的通用性。
标准化与可移植性
作为 C++ 标准的一部分,STL 在所有兼容标准的编译器和平台上行为一致,避免了因平台差异导致的代码修改成本。
内存管理优化
容器类(如 std::vector)自动管理内存,减少手动分配/释放内存的错误风险。智能指针(如 std::shared_ptr)进一步简化资源管理。
性能与扩展性
STL 设计注重效率,例如迭代器抽象避免了数据结构的直接暴露,同时允许用户自定义容器或算法与 STL 无缝协作。
2. string 类
什么是 string 呢?
C++ 中将字符串直接作为一种类型,也就是 string 类型,使用 string 类型创建的对象就是 C++ 的字符串。string 是一种高级的封装,string 中包含大量的方法,这些方法使得字符串的操作变得更加简单。
2.1 为什么要学习 string 类
在 C 语言中,字符串是以 '\0' 结尾的一些字符的集合,为了操作方便,C 标准库中提供了一些 str 系列的库函数,但是这些库函数与字符串是分离开的,不太符合 OOP 的思想,而且底层空间需要用户自己管理,稍不留神可能还会越界访问。
在 OJ 中,有关字符串的题目基本以 string 类的形式出现,而且在常规工作中,为了简单、方便、快捷,基本都使用 string 类,很少有人去使用 C 库中的字符串操作函数。
2.2 标准库中的 string 类
这里主要对 string 类对象常用的接口进行简单的讲解,更多的可以见 string 相关文档。
string 类相关文档:
2.2.1 string 类对象的常见构造
1. 最常见的三种构造:
default (1) string();
copy (2) string (const string& str);
from c-string (4) string (const char* s);
- (1) 空字符串构造子(默认构造子)
构造空的 string ,即空字符串。 - (2) 复制构造器
拷贝构造函数。 - (4) 来自 C 弦
用 C-string 来构造 string 类对象。
#include <iostream>
using namespace std;
int main()
{
string s1;//默认构造
string s2("12345");//带参构造
string s3(s2);//拷贝构造
cout << s1 << endl;
cout << s2 << endl;
cout << s3 << endl;
cin >> s1;
cout << s1 << endl;
return 0;
}

2. 其他几种常见构造
substring (3) string (const string& str, size_t pos, size_t len = npos);
from sequence (5) string (const char* s, size_t n);
fill (6) string (size_t n, char c);
range (7) template <class InputIterator>
string (InputIterator first, InputIterator last);
-
(3) 子字符串构造器
复制从角色位置 pos 开始并跨越 len 字符(或如果 str 太短或 len 是string::npos)直到 str 结束的部分。 -
(5) 来自缓冲区
从由 s 指向的字符数组中复制前 n 个字符。 -
(6) 填充构造器
用连续的 n 个字符 c 来填充字符串。 -
(7) 距离构造器
复制[first,last)范围内字符的序列,顺序相同。
string::npos:C++ 标准库中std::string类的一个静态成员常量,表示“无效位置”或“未找到”。它主要用于字符串操作函数(如 find()、rfind() 等)中,当搜索失败时返回这个值。其类型是 size_t(一个无符号整数类型),在大多数实现中,它被定义为 size_t 类型的最大值,通常等于 2 32 − 1 2^{32} - 1 232−1 或 2 64 − 1 2^{64} - 1 264−1,具体取决于系统架构。
#include <iostream>
using namespace std;
int main()
{
string s1;
string s2("12345678");
string s3(s2);
string s4(s2, 4, 15);
cout << s4 << endl;
string s5(s2, 4);
cout << s5 << endl;
string s6("hello world", 6);
cout << s6 << endl;
string s7(10, 'x');
cout << s7 << endl;
return 0;
}

2.2.2 string 类对象的访问及遍历操作
| 函数名称 | 功能说明 |
|---|---|
operator[](重点) | 返回 pos 位置的字符, const string 类对象调用 |
begin + end | begin 获取一个字符的迭代器 + end 获取最后一个字符下一个位置的迭代器 |
rbegin + rend | begin 获取一个字符的迭代器 + end 获取最后一个字符下一个位置的迭代器 |
| 范围 for | C++11 支持更简洁的范围 for 的新遍历方式 |
#include <iostream>
#include <string>
using namespace std;
void test_string()
{
string s1;
string s2("hello world");
cout << s1 << s2 << endl;
s2[0] = 'x';
cout << s1 << s2 << endl;
//下标 + []
for (size_t i = 0; i < s2.size(); i++)
{
cout << s2[i] << " ";
}
cout << endl;
//迭代器
//正向迭代器
string::iterator it = s2.begin();
while (it != s2.end())
{
*it += 2;
cout << *it << " ";
++it;
}
cout << endl;
//反向迭代器
string::reverse_iterator init = s2.rbegin();
while (init != s2.rend())
{
cout << *init << endl;
++init;
}
cout << endl;
//const类型
const string s3("hello");
string::const_iterator cit = s3.begin();
while (cit != s3.end())
{
cout << *cit << endl;
++cit;
}
cout << endl;
string::const_reverse_iterator rcit = s3.rbegin();
while (rcit != s3.rend())
{
cout << *rcit << endl;
++rcit;
}
cout << endl;
//范围for
//字符赋值,自动迭代,自动判断结束
//底层就是迭代器
for (auto ch : s2)
{
cout << ch << " ";
}
cout << endl;
}
int main()
{
test_string();
return 0;
}

#include <iostream>
#include <string>
using namespace std;
void test_string()
{
string s1;
string s2("hello world");
cout << s1 << s2 << endl;
s2[0] = 'x';
cout << s1 << s2 << endl;
//下标 + []
for (size_t i = 0; i < s2.size(); i++)
{
cout << s2[i] << " ";
}
cout << endl;
//迭代器
string::iterator it = s2.begin();
while (it != s2.end())
{
*it += 2;
cout << *it << " ";
++it;
}
cout << endl;
//范围for
for (auto ch : s2)
{
ch -= 2;
cout << ch << " ";
}
cout << endl;
cout << s2 << endl;
for (auto& ch : s2)
{
ch -= 2;
cout << ch << " ";
}
cout << endl;
cout << s2 << endl;
}
int main()
{
test_string();
return 0;
}

迭代器有四种:
iterator,const_iterator,reverse_iterator,const_reverse_iterator
2.2.3 auto 和范围 for
1. auto 关键字
-
在早期 C/C++ 中 auto 的含义是:使用 auto 修饰的变量,是具有自动存储器的局部变量,后来这个不重要了。C++11 中,标准委员会变废为宝赋予了 auto 全新的含义即:auto 不再是一个存储类型指示符,而是作为一个新的类型指示符来指示编译器,auto 声明的变量必须由编译器在编译时期推导而得。
-
用 auto 声明指针类型时,用 auto 和 auto* 没有任何区别,但用 auto 声明引用类型时则必须加 & 当在同一行声明多个变量时,这些变量必须是相同的类型,否则编译器将会报错,因为编译器实际只对第一个类型进行推导,然后用推导出来的类型定义其他变量。
-
auto 不能作为函数的参数,可以做返回值,但是建议谨慎使用。
-
auto 不能直接用来声明数组。
#include<iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
std::map<std::string, std::string> dict = { { "apple", "苹果" },{ "orange", "橙子" }, {"pear","梨"} };
// auto的用武之地
//std::map<std::string, std::string>::iterator it = dict.begin();
auto it = dict.begin();
while (it != dict.end())
{
cout << it->first << ":" << it->second << endl;
++it;
}
return 0;
}
#include<iostream>
using namespace std;
int func1()
{
return 10;
}
// 不能做参数
//void func2(auto a)
//{ }
// 可以做返回值,但是建议谨慎使用
auto func3()
{
return 3;
}
int main()
{
int a = 10;
auto b = a;
auto c = 'a';
auto d = func1();
// 编译报错:rror C3531: “e”: 类型包含“auto”的符号必须具有初始值设定项
//auto e;
cout << typeid(b).name() << endl;
cout << typeid(c).name() << endl;
cout << typeid(d).name() << endl;
int x = 10;
auto y = &x;
auto* z = &x;
auto& m = x;
cout << typeid(x).name() << endl;
cout << typeid(y).name() << endl;
cout << typeid(z).name() << endl;
auto aa = 1, bb = 2;
// 编译报错:error C3538: 在声明符列表中,“auto”必须始终推导为同一类型
//auto cc = 3, dd = 4.0;
// 编译报错:error C3318: “auto []”: 数组不能具有其中包含“auto”的元素类型
//auto array[] = { 4, 5, 6 };
return 0;
}
auto 做返回值时,可能会出现多重调用,需要一步步往上找,有些麻烦,而且不知道是什么类型,是仿照 python 语言新建的功能。
#include <iostream>
using namespace std;
auto func1()
{
//...
return 1;
}
auto func2()
{
//...
return func1();
}
auto func3()
{
//...
return func2();
}
int main()
{
auto ret = func3();
return 0;
}
2. 范围 for
- 对于一个有范围的集合而言,由程序员来说明循环的范围是多余的,有时候还会容易犯错误。因此 C++11 中引入了基于范围的 for 循环。for 循环后的括号由冒号
“ :”分为两部分:第一部分是范围内用于迭代的变量,第二部分则表示被迭代的范围,自动迭代,自动取数据,自动判断结束。 - 范围 for 可以作用到数组和容器对象上进行遍历。
- 范围 for 的底层很简单,容器遍历实际就是替换为迭代器,这个从汇编层也可以看到。
#include<iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
int array[] = { 1, 2, 3, 4, 5 };
// C++98的遍历
for (int i = 0; i < sizeof(array) / sizeof(array[0]); ++i)
{
array[i] *= 2;
}
for (int i = 0; i < sizeof(array) / sizeof(array[0]); ++i)
{
cout << array[i] << endl;
}
// C++11的遍历
for (auto& e : array)
e *= 2;
for (auto e : array)
cout << e << " " << endl;
string str("hello world");
for (auto ch : str)
{
cout << ch << " ";
}
cout << endl;
return 0;
}
2.2.4 string 类对象的容量操作
| 函数名称 | 功能说明 |
|---|---|
| size(重点) | 返回字符串有效字符长度 |
| length | 返回字符串有效字符长度 |
| capacity | 返回空间总大小 |
| empty(重点) | 检测字符串是否为空串,是返回true,否则返回false |
| clear(重点) | 清空有效字符 |
| reserve(重点) | 为字符串预留空间** |
| resize(重点) | 将有效字符的个数改成n个,多出的空间用字符c填充 |
size()与length()方法底层实现原理完全相同,引入size()的原因是为了与其他容器的接口保持一致,一般情况下基本都是用size()。clear()只是将 string 中有效字符清空,不改变底层空间大小。resize(size_t n)与resize(size_t n, char c)都是将字符串中有效字符个数改变到 n 个,不同的是当字符个数增多时:resize(n)用 0 来填充多出的元素空间,resize(size_t n, char c)用字符 c 来填充多出的元素空间。注意:resize 在改变元素个数时,如果是将元素个数增多,可能会改变底层容量的大小,如果是将元素个数减少,底层空间总大小不变。reserve(size_t res_arg=0):为 string 预留空间,不改变有效元素个数,当 reserve 的参数小于 string 的底层空间总大小时,reserver 不会改变容量大小。
#include <iostream>
using namespace std;
void TestPushBack()
{
string s;
size_t sz = s.capacity();
cout << "capacity changed: " << sz << '\n';
cout << "making s grow:\n";
for (int i = 0; i < 100; ++i)
{
s.push_back('c');
if (sz != s.capacity())
{
sz = s.capacity();
cout << "capacity changed: " << sz << '\n';
}
}
}
void test_string2()
{
string s2("hello world");
cout << s2.length() << endl;
cout << s2.size() << endl;
cout << s2.max_size() << endl;//string最大可以开多长,没什么意义受环境影响
cout << s2.capacity() << endl;
TestPushBack();
}
int main()
{
test_string2();
return 0;
}
- vs 2022 下扩容一开始是 2 倍扩容(因为从一块空间扩到另一块空间的特殊处理)后面是 1.5 倍扩容。

- g++ 下的就是直接是 2 倍扩容。

vs 和 g++ 下 string 结构的说明:
注意:下述结构是在 32 位平台下进行验证,32 位平台下指针占 4 个字节。
1. vs 下 string 的结构
string 总共占 28 个字节,内部结构稍微复杂一点,先是有一个联合体,联合体用来定义 string 中字符串的存储空间:
- 当字符串长度小于 16 时,使用内部固定的字符数组来存放;
- 当字符串长度大于等于 16 时,从堆上开辟空间。
union _Bxty
{ // storage for small buffer or pointer to larger one
value_type _Buf[_BUF_SIZE];
pointer _Ptr;
char _Alias[_BUF_SIZE]; // to permit aliasing
} _Bx;
这种设计也是有一定道理的,大多数情况下字符串的长度都小于 16,那 string 对象创建好之后,内部已经有了 16 个字符数组的固定空间,不需要通过堆创建,效率高。其次:还有一个 size_t 字段保存字符串长度,一个 size_t 字段保存从堆上开辟空间总的容量。
最后:还有一个指针做一些其他事情。故总共占16+4+4+4=28个字节。

2. g++ 下 string 的结构
G++ 下,string 是通过写时拷贝实现的,string 对象总共占 4 个字节,内部只包含了一个指针,该指针将来指向一块堆空间,内部包含了如下字段:
- 空间总大小;
- 字符串有效长度;
- 引用计数;
struct _Rep_base
{
size_type _M_length;
size_type _M_capacity;
_Atomic_word _M_refcount;
};
- 指向堆空间的指针,用来存储字符串。
2.2.5 string 类对象的修改操作
| 函数名称 | 功能说明 |
|---|---|
| insert | 在某一个位置前插入 |
| push_back | 在字符串后尾插字符 C |
| pop_back | 删除最后一个字符 |
| append | 在字符串后追加一个字符串 |
| erase | 字符串值中从字符位置 pos 开始并跨成 len 字符的部分(或直到字符串末尾,如果内容过短或 len 是 string::npos) |
| replace | 用新内容替换字符串中从字符 pos 开始并跨成 len 字符的部分 |
| operator+=(重点) | 在字符串后追加字符串 str |
| c_str | 返回 C 格式字符串 |
| find + npos(重点) | 从字符串 pos 位置开始往后找字符 C,返回该字符在字符串中的位置 |
| rfind | 从字符串 pos 位置开始往前找字符 C,返回该字符在字符串中的位置 |
| substr | 在 str 中从 pos 位置开始,截取 n 个字符,然后将其返回 |
- insert:

string& insert (size_t pos, const string& str); //pos位置前面插入一个string字符串
string& insert (size_t pos, const char* s); //pos位置前面插入一个C⻛格的字符串
string& insert (size_t pos, size_t n, char c);//pos位置前面插入n个字符c
//代码1
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = "abcdefghi";
string str = "xxx";
cout << s << endl;
s.insert(3, str);
cout << s << endl;
return 0;
}
//代码2
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = "abcdefghi";
cout << s << endl;
s.insert(3, "xxx");
cout << s << endl;
return 0;
}
//代码3
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = "abcdefghi";
cout << s << endl;
s.insert(3, 3, 'x');
cout << s << endl;
return 0;
}
- push_back:

#include <iostream>
#include<string> //添加string头文件
using namespace std;
int main()
{
//向空字符串中尾插字符
string s;
s.push_back('h');
s.push_back('e');
s.push_back('l');
s.push_back('l');
s.push_back('o');
cout << s << endl;
//向非空字符串中尾插字符
string s1 = "hello ";
s1.push_back('w');
s1.push_back('o');
s1.push_back('r');
s1.push_back('l');
s1.push_back('d');
cout << s1 << endl;
//批量插入字符
string s2;
for (char c = 'a'; c <= 'f'; c++)
{
s2.push_back(c);
}
cout << s2 << endl;
return 0;
}
- pop_back:

#include <iostream>
#include<string>
using namespace std;
int main()
{
string s = "hello";
cout << "s:" << s << endl;
//尾删
s.pop_back();
cout << "s:" << s << endl;
//尾删
s.pop_back();
cout << "s:" << s << endl;
return 0;
}
-
append 类似于 push_back 只不过由字符变为字符串。
-
erase:
string& erase (size_t pos = 0, size_t len = npos);
iterator erase (iterator p);
iterator erase (iterator first, iterator last);
#include <iostream>
#include <string>
int main ()
{
std::string str ("This is an example sentence.");
std::cout << str << '\n';
// "This is an example sentence."
str.erase (10,8); // ^^^^^^^^
std::cout << str << '\n';
// "This is an sentence."
str.erase (str.begin()+9); // ^
std::cout << str << '\n';
// "This is a sentence."
str.erase (str.begin()+5, str.end()-9); // ^^^^^
std::cout << str << '\n';
// "This sentence."
return 0;
}
- find:
find() 函数用于查找字符串中指定子串 / 字符,并返回子串 / 字符在字符串中第一次出现的位置。

size_t find (const string& str, size_t pos = 0) const;
//查找string类型的字符串str,默认是从头开始查找,pos可以指定位置开始
size_t find (const char* s, size_t pos = 0) const;
//查找C⻛格的字符串s,默认是从头开始查找,pos可以指定位置开始
size_t find (const char* s, size_t pos, size_t n) const;
//在字符串的pos这个位置开始查找C⻛格的字符串s中的前n个字符,
size_t find (char c, size_t pos = 0) const;
//查找字符c,默认是从头开始,pos可以指定位置开始
返回值:
- 若找到。返回子串/字符在字符串中第一次出现的起始下标位置。
- 若未找到。返回一个整数值 npos(针对 npos 的介绍会在下面给出)。通常判断 find() 函数的返回值是否等于npos就能知道是否查找到子串或者字符
//代码1
#include <iostream>
#include <string> //添加string头文件
using namespace std;
int main()
{
string s = "hello world hello everyone";
string str = "llo";
//查找string类型的字符串
size_t n = s.find(str);
cout << n << endl;
n = s.find(str, n + 1); //从n+1这个指定位置开始查找
cout << n << endl;
//查找C风格的字符串
n = s.find("llo");
cout << n << endl;
n = s.find("llo", n + 1); //从n+1这个指定位置开始查找
cout << n << endl;
return 0;
}
//代码2
#include <iostream>
#include <string> //添加string头文件
using namespace std;
int main()
{
string s = "hello world hello everyone";
//在s中,0这个指定位置开始查找"word"中的前3个字符
size_t n = s.find("word", 0, 3);
cout << n << endl;
n = s.find("everyday", n+1, 5);
cout << n << endl;
return 0;
}
//代码3
#include <iostream>
#include <string> //添加string头文件
using namespace std;
int main()
{
string s = "hello world hello everyone";
size_t n = s.find('o');
cout << n << endl;
n = s.find('o', n + 1);
cout << n << endl;
return 0;
}
//查找不到的情况 代码4
#include <iostream>
#include <string> //添加string头文件
using namespace std;
int main()
{
string s = "hello world hello everyone";
string str = "sanfengerwang";
size_t n = s.find(str);
cout << n << endl;
if(n != string::npos)
cout << "找到了,位置是:" << n << endl;
else
cout << "没有找到" << endl;
return 0;
}
- replace:
#include <iostream>
using namespace std;
int main()
{
string ss("hello world");
ss.erase(6);
cout << ss << endl;
string sss("hello world hello kangkang");
/*size_t pos = sss.find(' ');
while (pos != string::npos)
{
sss.replace(pos, 1, "%%");
cout << sss << endl;
pos = sss.find(' ', pos+2);
}
cout << sss << endl;*/
//sss.replace(5, 1, "%%");
//cout << sss << endl;
//因为replace替换会有后移操作,影响效率,一般最好的话可以创一个新字符串
string tmp;
tmp.reserve(sss.size());
for (auto ch : sss)
{
if (ch == ' ')
tmp += "%%";
else
tmp += ch;
}
cout << tmp << endl;
//sss = tmp;
sss.swap(tmp);
cout << sss << endl;
return 0;
}
- operator+=:

#include <iostream>
#include <string> //添加string头文件
using namespace std;
int main()
{
string s = "hello";
s += " world"; //字符串用双引号,等价于 s = s + " world"
cout << s << endl;
//除了+=操作,也可以使用'+'灵活进行字符串拼接
//1.尾部拼接
string s1 = "hello";
cout << s1 + " world" << endl; //s1仍然是"hello"
s1 = s1 + " world";
cout << s1 << endl; //s1是"hello world"
//2.头部拼接
string s2 = "hello";
s2 = "world " + s2 ;
cout << s2 << endl; //s2为:"world hello"
return 0;
}
- c_str:
#include <iostream>
using namespace std;
int main()
{
string file;
cin >> file;
FILE* fout = fopen(file.c_str(), "r");
char ch = fgetc(fout);
while (ch != EOF)
{
cout << ch;
ch = fgetc(fout);
}
fclose(fout);
}

- substr:
string substr (size_t pos = 0, size_t len = npos) const;
//pos 的默认值是0,也就是从下标为0的位置开始截取
//len 的默认值是npos,意思是一直截取到字符串的末尾
substr() :如果函数不传参数,就是从下标为0的位置开始截取,直到结尾,得到的是整个字符串;
substr(pos):从指定下标pos位置开始截取子串,直到结尾;
substr(pos, len):从指定下标pos位置开始截取长度为len的子串。


返回值类型:string,返回的是截取到的字符串,可以使用 string 类型的字符串接收。
#include <iostream>
#include<string> //添加string头文件
using namespace std;
int main()
{
string s = "hello world hello everyone";
string s1 = s.substr(7);
cout << s1 << endl;
string s2 = s.substr(7, 6);
cout << s2 << endl;
return 0;
}
2.2.6 string 类非成员函数
| 函数 | 功能说明 |
|---|---|
| operator+ | 尽量少用,因为传值返回,导致深拷贝效率低 |
| operator>>(重点) | 输入运算符重载 |
| operator<<(重点) | 输出运算符重载 |
| getline(重点) | 获取一行字符串 |
| relational operators(重点) | 大小比较 |
- getline:
cin 的方式给 string 类型的字符串中输入数据的时候,可以输入不带空格的字符串。但是如果带有空格,遇到空格也就读取结束了,没有办法正常读取,那怎么办呢?解决办法就是使用 getline。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
//输入
cin >> s;
//输出
cout << s << endl;
return 0;
}

getline 函数是 C++ 标准库中的一个函数,用于从输入流中读取一行文本,并将其存储 为字符串。
getline 函数有两种不同的形式,分别对应着字符串的结束方式。
istream& getline (istream& is, string& str);
istream& getline (istream& is, string& str, char delim);
- 第一种 getline 函数以换行符(‘\n’)作为字符串的结束标志,它的一般格式是:
getline(cin, string str)
//cin -- 表示从输入流中读取信息
//str 是存放读取到的信息的字符串
这种形式的 getline 函数从输入流(例如 cin)中读取文本,直到遇到换行符(‘\n’)为止,然后将读取到的文本(不包括换行符)存储到指定的 string 类型的变量 str 中。
#include<iostream>
#include <string>
using namespace std;
int main ()
{
string name;
getline (cin, name);
cout << name << endl;
return 0;
}

- 第二种 getline 函数允许用戶自定义结束标志,它的一般格式是
getline(cin, string str, char delim)
//cin -- 表示从输入流中读取信息
//str 是存放读取到的信息的字符串
//delim 是自定义的结束标志
#include<iostream>
#include <string>
using namespace std;
int main ()
{
string name;
getline (cin, name, 'e');
cout << name << endl;
return 0;
}

上面的几个接口大家了解一下,在以后的 OJ 题目中会有一些体现他们的使用。string 类中还有一些其他的操作,这里不一一列举,大家在需要用到时不明白了查文档即可。
结语
string 类作为 C++ STL 的核心组件之一,其灵活性与高效性为字符串处理提供了强大支持。通过深入剖析其常用接口、底层结构及编译器差异,开发者能够更精准地掌握字符串操作的底层逻辑,避免常见陷阱。
从构造、访问、遍历到容量管理、修改操作,string 类的设计体现了 STL 的泛型编程思想。不同编译器的实现差异也提醒我们,在跨平台开发时需关注底层细节。
掌握 string 类不仅提升代码效率,更是理解 STL 设计理念的重要一步。未来在复杂项目或性能优化中,这些知识将成为不可或缺的基石。
愿诸君能一起共渡重重浪,终见缛彩遥分地,繁光远缀天。


713

被折叠的 条评论
为什么被折叠?



