一、构造函数
1.默认构造函数(defalut constructor):string()
2.指针拷贝构造函数(from c-string):string(const char* s)
3.拷贝构造函数(copy constructor):string(const string& str)
4.子串构造函数(substring constructor):string(const string& str, size_t pos, size_t len = npos)
npos的定义:static const size_t npos = -1,整型-1转换为无符号整型数表示size_t的最大值4,294,967,295。pos用于定位子串开始位置,len表示子串的长度,len的默认参数是npos,如果len值大于等于剩余子串长度或者没有提供len值,子串将直接取到str结尾。
5.指针限定拷贝构造函数(from buffer):string(const char* s. size_t n)
拷贝字符串的前n个字符
6.填充构造函数(fill constructor):string(size_t n, char c)
n个字符c构造成字符串
cpp
string s1;//默认构造函数
string s2("i love gjj");//指针拷贝构造函数
string s3(s2);//拷贝构造函数
string s4(s3, 7, 3);//子串构造函数
string s5("love from gjj", 4);//指针限定拷贝构造函数
string s6(10, '$');//填充构造函数
cout << s1 << endl;
cout << s2 << endl;//i love gjj
cout << s3 << endl;//i love gjj
cout << s4 << endl;//gjj
cout << s5 << endl;//love
cout << s6 << endl;//$$$$$$$$$$
二、赋值运算符重载
1.string& operator= (const string& str)
2.string& operator= (const char* s)
3.string& operator= (char c)
cpp
string s1, s2, s3;
s1 = "love from gjj";
s2 = s1;
s3 = 'j';
三、string类的访问
string类提供三种访问方法:下标+[ ]运算符重载、迭代器、范围for循环
1.下标+[ ]运算符重载
cpp
string s1("i miss gjj");
for (size_t i = 0; i < s1.size(); i++)
{
cout << s1[i] << " ";
}
cout << endl;
2.迭代器
cpp
//正向迭代器
string::iterator it1 = s1.begin();
while (it1 != s1.end())
{
cout << *it1 << " ";
++it1;
}
cout << endl;
//反向迭代器
string::reverse_iterator rit = s1.rbegin();
while (rit != s1.rend())
{
cout << *rit << " ";
++rit;
}
cout << endl;
3.范围for循环
cpp
for (auto e : s1)
{
cout << e << " ";
}
cout << endl;