文章目录
1 string类
- string是表示字符串的字符串类,是管理字符数组的类。
- 该类的接口与常规容器的接口基本相同,再添加了一些专门用来操作string的常规操作。
- string在底层实际是:basic_string模板类的别名,typedef basic_string<char, char_traits, allocator>string;。
- 不能操作多字节或者变长字符的序列。
- 头文件:<string>
2 常用接口
2.1 构造函数
- string():构造一个空字符串
- string(const string& str):拷贝构造函数
- string(const char* s):用C-string来构造string类对象
代码演示
string s1;
string s2("hello world");
string s3(s2); // 拷贝构造
cout << "s1 = " << s1 << endl;
cout << "s2 = " << s2 << endl;
cout << "s3 = " << s3 << endl;
运行结果
2.2 capacity容量相关接口
- size():返回字符串有效字符串长度
- length():同size(),但size()更通用
- empty():检测字符串是否为空串,空则返回true,非空返回false
- clear():清空有效字符,但不改变底层空间大小
- capacity():返回空间总大小
- reserve():为字符串预留空间
- resize(size_t n,char c):将有效字符的个数变为n个,多出的用字符c填充,缺省值为0
代码演示
string s1;
string s2("hello world");
string s3(s2); // 拷贝构造
cout << "s2.size = " << s2.size() << endl;
cout << "s2.capacity = " << s2.capacity() << endl;
cout << "s2.empty = " << s2.empty() << endl;
cout << "s1.empty = " << s1.empty() << endl;
cout << "——s2.clear——" << endl;
s2.clear();
cout << "s2 = " << s2 << endl;
cout << "s2.size = " << s2.size() << endl;
cout << "s2.capacity = " << s2.capacity() << endl; //clear不改变capacity
cout << "s2.empty = " << s2.empty() << endl;
cout << "——s2.resize(10)——" << endl;
s2.resize(10,'a'); // 设置长为10且用a填充
cout << "s2 = " << s2 << endl;
cout << "s2.size = " << s2.size() << endl;
cout << "s2.capacity = " << s2.capacity() << endl;
cout << "s2.empty = " << s2.empty() << endl;
运行结果
2.3 string对象的访问及遍历
2.3.1 for循环+operator[]
operator[]:返回pos位置的字符
2.3.2 迭代器
begin:获取一个字符的迭代器
end:获取最后一个字符的迭代器
rbegin:获取最后一个字符的迭代器
rend:获取第一个字符的迭代器
2.3.3 范围for(语法糖)
C++11支持的for的新遍历方式,auto自动推演数据类型
注意:范围for修改变量需要加引用,否则修改的只是临时变量
代码演示
// string遍历方式
string s1 = "hello world";
cout << s1<<endl;
// 1.operator[]
cout << "operator[]:" << endl;
for (size_t i = 0; i < s1.size(); i++) {
cout << s1[i] << " ";
}
cout << endl;
// 2. 迭代器iterator
cout << "迭代器:" << endl;
string::iterator it = s1.begin();
while (it != s1.end()) {
cout << *it << " ";
++it;
}
cout << endl;
// 反向迭代器reverse_iterator
cout << "反向迭代器:" << endl;
string::reverse_iterator rit = s1.rbegin();
while (rit != s1.rend()) {
cout << *rit << " ";
++rit;
}
cout << endl;
// 3. 语法糖范围for
cout << "范围for:" << endl;
for (auto i : s1) {
cout << i << " ";
}
cout << endl;
运行结果
2.4 string类对象的修改操作
- operator+=:在字符串后面追加字符串str
- push_back():在字符串后尾插字符c
- append():在字符串后追加字符c
- c_str():返回C格式字符串
- find(c,pos):从pos位置开始向后查找字符c,返回值为该字符在字符串中的位置,没找到返回常量string::pos
- rfind(c,pos):从pos位置开始向前查找字符c,返回值为该字符在字符串中的位置
- substr(pos,n):从pos开始截取n个字符并将其返回
2.5 string类非成员函数
- operator+:拼接字符串
- operator>>:输入运算符重载
- operator<<:输出运算符重载
- getline:获取一行字符串
- relational operators:大小比较