string类
在C语言 中,我们总是用char* 的类型来创建一个变量,存储一个字符串;当我们想对它进行修改或者读写时,需要自我创建空间和使用string.h的库函数来进行操作它;
而在C++中,C++专门提供了一个头文件 string 用一个类对字符串的一系列操作进行了封装;对于底层空间不需要用户自己管理了;
当然该类是basic_string类的一个实例 ,使用了char来实例化basic_string模板类;
这个类独立于所使用的编码来处理字节:如果用来处理多字节或变长字符(如UTF-8)的序列,这个类的所有成员(如长度或大小)以及它的迭代器,将仍然按照字节(而不是实际编码的字符)来操作。
接下来就详细介绍string类的使用。
创建一个string类的对象

对于string类的使用,我们首先就必须引用它的头文件
#include < string >
cpp
string s1; //默认的创建一个String对象
string s2("One more thing"); //用C-Stirng来创建Strng类的对象s2
string s3 = s2; //构造拷贝函数
string s4(s2); //构造拷贝函数
cout << s1 << endl;
cout << s2 << endl;
cout << s3 << endl;
cout << s4 << endl;
对创建的类进行查看
查看对指定字符串的指定子字符串的使用
cpp
string s5(s2, 5, 6);//复制指定字符串的子串
cout << s5 << endl;
string s6(s2, 1); //从第1个元素进行复制构造
cout << s6 << endl;
string s7(s2, 5, 100);
cout << s7 << endl;
npos
cpp
string s8("One More", 5);//从首个元素复制到指定第5个元素之前
cout << s8 << endl;
string s9(5, 'c');//复制5个c字符
cout << s9 << endl;
赋值操作
赋值时该对象必须是已经存在 的;
cpp
string s1;
s1 = 'x';
s1 = s2;
s1 = "hello";
遍历和访问
size() 和 lenth()


操作数[]
可以直接访问对应字符串的元素
逆置字符串
iterator
iterator迭代器,是C++标准库中的一个概念。它是一种对象,用于遍历容器中的元素序列,以访问和处理容器中的元素。
对于string类来说,terator本质上就是就是一个字符串指针,指向字符串的某个位置,从而允许我们遍历容器中的所有元素,而不需要了解string本身的结构和实现细节。
而C++中,有一个reverse的函数模板
const问题
要注意const和会非const的区别
rbegin()和rend()

back()和front()
reserve

在Linux的g++中
g++中:
g++中
结论:
risize()

插入

push_back()
append()
操作数+=
追加字符时与push_back()一样;追加字符串时,和append()效果一样。
insert
erase

删除指定字符串。
find()

rfind


c_str

find_first_of
find_last_of
operator+
getline