目录
1.string类简介
【标准库中的string类】:
- 字符串是表示字符序列的类
- 标准的字符串类提供了对此类对象的支持,其接口类似于标准字符容器的接口,但添加了专门用于操作单字节字符字符串的设计特性。
- string在底层实际是:basic_string模板类的别名,typedef basic_string<char, char_traits, allocator>string;
- 这个类独立于所使用的编码来处理字节。如果用来处理多字节或变长字符,如UTF-8序列,这个类的所有成员以及它的迭代器,将仍然按照字节而不是实际编码来操作。总而言之,不能操作多字节或者变长字符的序列。
- 在使用string类时,必须包含头文件#include<string>
2.String类的常用接口说明
string类对象的常见构造
std::string(constructor) 对于这个文档会对C++中的string类有详细解释。
- string() 构造空的string类对象,即空字符串
- string (const string& str) 用另一个类对象拷贝构造当前类对象
- string(const char* s) 用字符串初始化
- string (const string& str, size_t pos, size_t len = npos) 用另一个类对象的pos位置直到len位置初始化当前类对象,当len有值且小于字符串长度,那么初始化的就是pos到len的位置,如果len超过字符串长度,或者没有给值,用了npos缺省值,那么截取的str范围就是pos的位置直到最后,有多少取多少。
- 这里pos和npos在文档中都有解释,npos是len的缺省值,因为npos是一个静态变量,值为-1,它的补码是32个1,size_t变成无符号数,补码是31个1,对应的原码数字是42亿,这就造成了范围远远大于字符串长度。
- string (const char* s, size_t n) 用一个字符串,取字符串的前n个来初始化字符类对象。但是对于这个用法有点鸡肋,如果想取前n个来初始化,直接用前n个初始化就好了。
- string (size_t n, char c) 用n个char字符c来初始化字符类对象。
int main()
{
string s1;
string s2("hello world");
string s3(s2);
cin >> s1;
cout << s1 << endl;
cout << s2 << endl;
cout << s3 << endl;
string s4(s2, 2, 6);//很少用这个
cout << s4 << endl;
string s5(s2, 2);//没给范围或者范围超过字符串长度,有多少取多少
string s6(s2, 2, 100);
cout << s5 << endl;
cout << s6 << endl;
string s7("hello world", 3);
//string s7("hel");
cout << s7 << endl;
string s8("i am a student.", 4);
cout << s8 << endl;
string s9(10, '!');
cout << s9 << endl;
return 0;
}
string类的容量操作
- size 返回字符串有效字符长度(不包括\0)
- length 同上
- max_size 返回最大字符串长度,一般长度是42亿(实际意义不大)
- capacity 查看空间容量大小是多少
- clear 把有效数据全清理掉
- empty 判断是否为空
- shrink_to_fit(C++11) 释放口面所有的容量
string s1;
cin >> s1;
cout << s1.size() << endl;
cout << s1.length() << endl;
cout << s1.max_size() << endl;
cout << s1.capacity() << endl;
s1.clear();
cout << s1 << endl;
cout << s1.capacity() << endl;//只是把数据清掉,容量没有清掉
string的访问及遍历
- operator[] 返回pos位置的字符,实际上是[]的一个重载。底层代码返回值为char&,起初是为了减少拷贝,但是在这里是为了得到字符串,在有些代码实现中,返回字符的引用,可以修改该位置的字符串值(出了作用域还在,都在堆上)
- at[] 与operator[]类似,但是二者检查越界有区别,operaotr[]通过断言检查越界,at