一、创建string对象
1、文档
2、常用
并不是所有的用法都需要熟记于心,我们只需记住常用的即可,对于并不常用的,我们可以在用到的时候查看文档学习使用。
void Test1()
{
string s1;
string s2("Hello World");
s1 = "Hello World";
//从第六(从0开始计算)个位置开始,打印5个
string s3(s1, 6, 5);
cout << s1 << " " << s3 << endl;
string s4(s1, 6);
cout << s4 << endl;
string s5(s1, 6,s1.size() - 6);
cout << s5 << endl;
string s7(10, 'a');
cout << s7 << endl;
}
二、运算符重载
1、[]
(1)文档
(2)使用
对于string,我们可以像对数组那样,使用[],即通过下标的方式,来读写string中的内容。
void Test2()
{
string s1 = "Hello World";
for (int i = 0; i < s1.size(); i++)
{
cout << s1[i] << " ";
}
cout << endl;
for (size_t i = 0; i < s1.size(); i++)
{
s1[i]++;
}
for (int i = 0; i < s1.size(); i++)
{
cout << s1[i] << " ";
}
cout << endl;
s1[0] = 'A';
cout << s1 << endl;
}
2、+
(1)文档
(2)使用
string类对象可+string类对象/字符串/单个字符
void Test8()
{
string s1 = "aaaaa";
string s2("Hello World");
cout << s2 << endl;
cout << s1 << endl;
string s3 = s1 + s2;
cout << s3 << endl;
s3 = s2 + "你好";
cout << s3 << endl;
s3 = s1 + 'b';
cout << s3 << endl;
}
3、+=
(1)文档
(2)使用
与+类似。
void Test8()
{
string s1 = "aaaaa";
string s2("Hello World");
cout << s1 << endl;
cout << s2 << endl;
s1 += " ccccc";
cout << s1 << endl;
s2 += 'x';
cout << s2 << endl;
s2 += s1;
cout << s2 << endl;
}
三、迭代器
1、迭代器
[begin,end):左闭右开区间,即: begin指向第一个位置,end指向最后一个位置的后一个位置
void Test3()
{
string s1 = "Hello World";
//迭代器
//[begin,end)
string::iterator it = s1.begin();
while (it != s1.end())
{
cout << *it << " ";
++it;
}
cout << endl;
it = s1.begin();
while (it != s1.end())
{
(*it)++;
cout << *it << " ";
++it;
}
cout << endl;
}
2、反向迭代器
注意:这里迭代还是使用“++”,而非“--”
void Test4()
{
string s1 = "Hello World";
//反向迭代器
//[begin,end)
//string::reverse_iterator rit = s1.rbegin();
auto rit = s1.rbegin();//auto自动推演类型
while (rit != s1.rend())
{
cout << *rit << " ";
++rit;
}
cout << endl;
rit = s1.rbegin();
while (rit != s1.rend())
{
(*rit)++;
cout << *rit << " ";
++rit;
}
cout << endl;
//范围for原理:编译器将其替换成迭代器
for (auto ch : s1)
{
cout << ch << " ";
}
cout << endl;
}
3、const string
void func(const string& s)
{
string::const_iterator it = s.begin();
while (it != s.end())
{
cout << *it << " ";
it++;
}
cout << endl;
string::const_reverse_iterator rit = s.rbegin();
while (rit != s.rend())
{
cout << *rit << " ";
rit++;
}
cout << endl;
}
void Test5()
{
string s1 = "Hello World";
func(s1);
}