目录
一:概述
- string是表示字符串的字符串类
- 该类的接口与常规容器的接口基本相同,再添加了一些专门用来操作string的常规操作。
- string在底层实际是:basic_string模板类的别名,typedef basic_string<char, char_traits, allocator> string;
- 不能操作多字节或者变长字符的序列
二:常用接口示例
1.常见的构造函数
string()
| 构造空的string类对象,即空字符串 |
string(const char* s)
|
用C-string来构造string类对象
|
string(size_t n, char c)
|
string类对象中包含n个字符c
|
string(const string&s)
|
拷贝构造函数
|
2.获取string类对象的容量
<1>: size
size
|
返回字符串有效字符长度
|
<2>: empty
empty
|
检测字符串释放为空串,是返回true,否则返回false
|
<3>: clear
clear |
清空有效字符
|
<4>: resize
resize |
将有效字符的个数该成n个,多出的空间用字符c填充
|
<5>:reserve
reserve |
为字符串预留空间
|
3.string类对象的访问及遍历
<1>:operator[]
operator[] |
返回pos位置的字符,const string类对象调用
|
<2>:begin+ end
begin+ end |
begin获取一个字符的迭代器 + end获取最后一个字符下一个位置的迭代器
|
<3>:rbegin + rend
rbegin + rend |
begin获取一个字符的迭代器 + end获取最后一个字符下一个位置的迭代器
|
通过调试查看现象:
<4>:范围 for
范围 for |
C++11支持更简洁的范围 for 的新遍历方式
|
4.string类对象的修改操作
<1>:push_back
push_back | 在字符串后面尾插字符 |
<2>:append
append | 在字符串后面追加一个字符串 |
<3>:operator+=
operator+= | 在字符串后面追加一个字符串 str |
<4>:c_str
c_str | 以C语言的方式打印字符串 |
<5>:find + npos
find + npos |
从字符串pos位置开始往后找字符c,返回该字符在字符串中的位置
|
<6>:rfind
rfind |
从字符串pos位置开始往前找字符c,返回该字符在字符串中的位置
|
<7>:substr
substr |
在str中从pos位置开始,截取n个字符,然后将其返回
|
5.string类非成员函数
<1>:operator+
operator+ |
尽量少用,因为传值返回,导致深拷贝效率低
|
<2>:operator>>
operator>> |
输入运算符重载
|
<3>:operator<<
operator<< |
输出运算符重载
|
<4>:getline
getline |
获取一行字符串
|
<5>:relational operators
relational operators |
大小比较
|