1.string类常用接口的说明
1.1string类对象的常见构造
函数名称 | 功能说明 |
string() | 构造空的string类对象,即空字符串 |
string(const char* s) | 用字符串来构造string类对象 |
string(size_t n , char c) | string类对象中包含n个字符c |
string ( const string& str ) | 拷贝构造函数 |
string ( const sting& str, size_t pos,size_t len = npos ) | 拷贝字符串str从pos位置开始的len个字符 |
void test_string1()
{
string s1; //构造
string s2("hello");
string s3(s2, 1, 3); //拷贝字符串str从pos位置开始的n个字符
string s4(5, 'a');
string s5(s4);//拷贝构造
cout << s1 << endl;
cout << s2 << endl;
cout << s3 << endl;
cout << s4 << endl;
cout << s5 << endl;
}
1.2. string类对象的容量操作
函数名称 | 功能说明 |
size | 返回字符串有效长度 |
lenth | 返回字符串有效长度 |
capacity | 返回空间总大小 |
empty | 检测字符串是否为空串,是返回true,否则返回false |
clear | 清空字符串(但空间不会被清理) |
reverse | 字符串容量适应计划中大小变化 |
resize void resize (size_t n); void resize (size_t n, char c); | 将有效的字符改成n个,其余多出的空间用字符c填充 |
void test_string4()
{
string s1("hello world");
string s2("hello");
cout << s1.size() << endl;
cout << s2.size() << endl;
cout << s1.length() << endl;
cout << s2.length() << endl;
cout << s1.max_size() << endl;//max_size 没有实际意义用处不大
cout << s1.max_size() << endl;
s1.clear(); //将s1清理掉,空间是否释放掉了呢? 否
cout << s1 << endl;
cout << s1.capacity() << endl;
cout << s1.empty() << endl; //判断是否为空,空返回1,非空返回0
cout << s2.empty() << endl;
}
1.3. string类对象的访问及遍历操作
函数名称 | 功能说明 |
operator [ ] | 返回pos位置的字符,const string类对象调用 |
begin + end | begin获取一个字符的迭代器 + end 获取最后一个字符后一个位置的迭代器 |
rbegin + rend | begin获取一个字符的反转迭代器 + end 获取最后一个字符后一个位置的反转迭代器 |
void test_string2()
{
string s1("hello");
s1 += " ";
s1 += "world";
cout << s1 << endl;
for (size_t i = 0;i < s1.size(); i++)
{
s1[i] += 1;
}
for (size_t i = 0; i < s1.size(); i++)
{
cout << s1[i] << " ";
}
cout << endl;
//迭代器
string::iterator it = s1.begin();
while (it != s1.end())
{
*it -= 1;
it++;
}
it = s1.begin();
while (it != s1.end())
{
cout << *it;
it++;
}
cout << endl;
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
vector<int>::iterator vit = v.begin();
while (vit != v.end())
{
cout << *vit << " ";
vit++;
}
cout << endl;
//范围for
//C++11 原理被替换成迭代器
for (auto ch : s1)
{
cout << s1 << " ";
}
cout << endl;
}
补充:迭代器iterator分为几种
根据方向分:正向(iterator)和反向(reverse_iterator)
属性:const 和 非const
1.4. string类对象的修改操作
函数名称 | 功能说明 |
push_back | 在字符串后尾插字符c |
append | 在字符串后追加字符串 |
operator+= | 在字符串后追加字符串 |
insert | 在指定位置后面插入 |
erase | 消除部分字符 |
void test_string5()
{
//string s1;
//s1.push_back('x');
//s1.append("xxxx");
//s1 += 'x';
//s1 += "xxx";
//cout << s1 << endl;
string s;
s += '1';
s += "2345";
cout << s << endl;
s.insert(s.begin(), '0');
cout << s << endl;
s.insert(2, "2");
cout << s << endl;
}