- string类
- string是表示字符串的字符串类;
- 该类的接口与常规容器的接口基本相同,再添加了一些专门用来操作string的常规操作;
- string在底层实际是:basic_string模板类的别名,typedef basic_string<char, char_traits, allocator> string;
- 不能操作多字节或者变长字符的序列。 在使用string类时,必须包含#include头文件以及using namespace std。
- string类对象的常见构造
- string() --> 构造空的string类对象,即空字符串;
- string(const char* s) --> 用C-string来构造string类对象;
- string(const string& s) --> 拷贝构造函数。
void Teststring()
{
string s1; //构造空的string类对象s1
string s2("hello world"); // 用C格式字符串构造string类对象s2
string s3(s2);//拷贝构造s3
}
void test_string()
{
//四个默认成员函数
string s1;//ok
string s2("hello");//ok
string s3(s2); //ok
string s4("hello", 2);
string s5(s2, 1, 8);
string s6(s2, 1);
string s7(10, 'a');
cout << s1 << endl;
cout << s2 << endl;//hello
cout << s3 << endl;//hello
cout << s4 << endl;//he
cout << s5 << endl;//ello
cout << s6 << endl;//ello
cout << s7 << endl;//aaaaaaaaaa
s1 = s7;//ok
cout << s1 << endl;//aaaaaaaaaa
}
- string类对象的容量操作
- size(length) --> 返回字符串有效字符长度;
- empty --> 检测字符串是否为空,是返回true,否则返回false;
- clear --> 清空有效字符,不改变底层空间大小。
- reserve --> 为字符串预留空间,不改变有效元素个数,当reserve的参数小于 string的底层空间总大小时,reserver不会改变容量大小。
- resize--> 将有效字符的个数改成n个,当字符个数增多时:resize(n)用0来填充多出的元素空间,resize(size_t n, char c)用字符c来填充多出的元素空间。resize在改变元素个数时,如果是将元素个数增多,可能会改变底层容量的大小,如果是将元素个数减少,底层空间总大小不变。
void test_string()
{
string s1("hello world");
string s2("hello");
cout << s1.size() << endl;//11
cout << s2.size() << endl;//5
cout << s1.length() << endl;//11
cout << s2.length() << endl;//5
cout << s1.max_size() << endl;//4294967294
cout << s2.max_size() << endl;//4294967294
cout << s1.capacity() << endl;//15
cout << s2.capacity() << endl;//15
s1 += "111111";
cout << s1.capacity() << endl;//31
s1.clear();
cout << s1 << endl;//空
cout << s1.capacity() << endl;//31
s1.reserve(100);
cout << s1.capacity() << endl;
s1.resize(100, 'x');
cout << s1.capacity() << endl;
cout << s1 << endl;
}
- string类对象的访问及遍历操作
- operator[] --> 返回pos位置的字符,const string类对象调用;
- begin + end --> begin获取一个字符的迭代器+end获取最后一个字符下一个位置的迭代器;
- 范围for。
void test_string()
{
string s1("hello");
s1 += ' ';
s1 += "world";
cout << s1 << endl;
//1、[] +下标
//读
for (size_t i = 0; i < s1.size(); ++i)
{
cout << s1[i] << " ";
}
cout << endl;
//写
for (size_t i = 0; i < s1.size(); ++i)
{
s1[i] += 1;
cout << s1[i] << " ";
}
cout << endl;
//2、迭代器
//写
//string::iterator it = s1.begin();
auto it = s1.begin();
while (it != s1.end())
{
*it -= 1;
++it;
}
//读
it = s1.begin();
while (it != s1.end())
{
cout << *it << " ";
++it;
}
cout << endl;
//3、范围for
//C++11 --> 原理被替换成迭代器
for (auto ch : s1)
{
cout << ch << " ";
}
cout << endl;
}
void test_string()
{
//反向迭代器
string s1("hello world");
string::reverse_iterator rit = s1.rbegin();
while (rit != s1.rend())
{
cout << *rit << " ";
++rit;
}
cout << endl;
}
- 字符串转整型
void string2int(const string& str) { int val = 0; //const迭代器 只能读不能写 string::const_iterator it = str.begin(); while (it != str.end()) { val *= 10; val += (*it - '0'); ++it; } cout<<val<<endl; }