标准库中的string类
string类
- 字符串是表示字符序列的类;string类是使用char作为它的字符类型;
- string类是basic_string模板的一个实例,它使用char来实例化basic_string模板类 ,并用char_traits和allocator作为basic_string的默认参数;
- string在底层实际上是:basic_string模板类的别名,typedef basic_string<char,char_traits,allocator> string;
- 不操作多字节或者变长字符的序列
string类的常用接口
1. string类对象的常见构造
2. string类对象的元素访问
- operator[] – 返回pos位置的字符,const string类对象调用
- at – 返回字符在字符串中的位置引用
- back – 返回字符串的最后一个字符
- front – 返回字符串的第一个字符的引用
- 范围for实际上是通过迭代器实现的,支持迭代器访问的自定义类型都可以支持范围for。
3. string类对象的迭代器
void test()
{
//正向迭代器
string str = "12345";
//起始位置的迭代器
string::iterator it1 = str.begin();
for (; it1 != str.end(); ++it1)
{
//迭代器的解引用
cout << *it1 << " ";
//通过迭代器进行内容的修改
*it1 = 'a';
}
const string str2 = "abcde";
//只读迭代器 不能修改内容
string::const_iterator it2 = str2.begin();
while (it2 != str2.end())
{
cout << *it2 << " ";
++it2;
}
}
//输出结果:1 2 3 4 5 a b c d e
vvoid test4()
{
//反向迭代器
string str = "12345";
//最后一个元素的位置
string::reverse_iterator it = str.rbegin();
while (it != str.rend())
{
cout << *it << " ";
//反向移动
++it;
}
//只读反向迭代器:不支持修改
const string str2 = "abcde";
string::const_reverse_iterator it2 = str2.rbegin();
while (it2 != str2.rend())
{
cout << *it2 << " ";
++it2;
}
}
//输出结果:5 4 3 2 1 e d c b a