String类
(1) 常用接口–string 对象的常见构造
int main()
{
string s0; // 构造空的string类对象,即空字符串
string s1("hello world"); // 使用C-string 构造string类对象
string s2(s1); // 拷贝构造
// 从s2 第4个位置的索引处开始,连续10个字符,组成的字符串构造string类对象。
// 如果指定长度10大于从索引位置到字符串结尾的长度,则直接到字符串结尾。
string s3(s2, 4, 10);
// 如果不指定长度,则到字符串结尾。
string s4(s2, 4);
// 如果指定长度小于从索引位置到字符串结尾的长度,且指定长度大于等于0,则按实际长度。
string s5(s2, 4, 0);
// 如果指定长度为负数,则从索引处到字符串结尾。
string s6(s2, 4, -2);
int i = 0;
cout << i++ << "->" << s0 << endl;
cout << i++ << "->" << s1 << endl;
cout << i++ << "->" << s2 << endl;
cout << i++ << "->" << s3 << endl;
cout << i++ << "->" << s4 << endl;
cout << i++ << "->" << s5 << endl;
cout << i++ << "->" << s6 << endl;
return 0;
}
(2) string对象的容量操作
- size (重点)返回字符串有效长度(不包含‘\0’)
- length 返回字符串有效长度(不包含‘\0’),和size相同,推荐使用size;
- capacity 返回空间总大小
- empty (重点)检测字符串释放为空串,是返回true, 否返回false
- clear (重点)清空有效字符, 不改变底层空间。
- reserve(重点)为字符串预留空间
- resize(重点)将有效字符的个数改成n个,多出的空间用字符c 填充
(3) string 对象的访问及遍历
class String
{
public:
// [] 运算符重载
char& operator[](size_t pos)
{
return _str[pos];
}
private:
char* _str;
size_t _size;
size_t _capacity;
};
-
[ i ] 遍历。底层原理是operator[] 的操作符重载
string s("hello world"); for (int i=0; i<s.size(); ++i) { cout << s[i] << " "; } cout << endl;
-
迭代器iterator
string::iterator it = s.begin(); while (it != s.end()) { cout << *it << " "; ++it; } cout << endl;
-
// 正向迭代器 iterator begin(); iterator end(); // 反向迭代器 reverse_iterator rbegin(); reverse_iterator rend(); // const 迭代器 const_iterator begin() const; const_iterator end() const;
-
范围for, 底层原理是迭代器
for (auto e : s) { cout << e << " "; } cout << endl;