目录
6.string类的常用接口说明(下面我们只讲解最常用的接口)
1. 什么是STL
STL(standard template libaray-标准模板库):是C++标准库的重要组成部分,不仅是一个可复用的组件库,而且 是一个包罗数据结构与算法的软件框架。
2. STL的版本
3. STL的六大组件

网上有句话说:“不懂STL,不要说你会C++”。STL是C++中的优秀作品,有了它的陪伴,许多底层的数据结构 以及算法都不需要自己重新造轮子,站在前人的肩膀上,健步如飞的快速开发。
4.STL的缺陷
5.string类
1. 为什么学习string类?
C语言中的字符串
 标准库中的string类
 string类(了解)
 在学习这类容器的时候我们建议是结合着文档一起:在这里推荐cplusplus  
6.string类的常用接口说明(下面我们只讲解最常用的接口)
1.string 常见构造

 我们能看到光构造函数就有7个
 通过文档我们能知道:
 
 我们能看到这个npos是一个静态的常量给的值是-1;为什么?
 因为是size_t 是一个无符号整数 是整型的最大值
提供多种初始化方式
#include<iostream>
#include<string>
using namespace std;
void test_string1()
{
	string s;   //构造空的string类对象 s
	string s1("hello world");  //用c类字符串构造
	string s2(s1);   //拷贝构造
	string s3(s1, 5);
	string s4(s1, 5,3);
 
   //这里能直接打印是因为库里面已经重载了
	cout << s << endl;
	cout << s1 << endl;
	cout << s2 << endl;
	cout << s3 << endl;
	cout << s4 << endl;
}
int main()
{
	test_string1();
	return 0;
}
 2.string类的遍历
  
 
 

void test_string2()
{
	string s1("hello world");
	for (size_t i = 0; i < s1.size(); ++i)
	{
		cout << s1[i] << " ";
	}
	cout << endl;
}
void test_string3()
{
	string s3("hello world");
	cout << s3[4] << endl;
	cout << s3.at(4) << endl;
    //at和【】一样在使用功能上并无差异 对于越界的检查有所不同
}iterator 迭代器遍历 (主流)通用的遍历方式
string s3(s1);
	string::iterator it3 = s3.begin();  //可读可写
	while (it3 != s3.end())
	{
		cout << *it3 << " ";
		++ it3;
	}
	cout << endl;
反向迭代器
string::reverse_iterator rit = s1.rbegin();   
	while (rit != s1.rend())
	{
		cout << *rit << " ";
		++rit;
	}
	cout << endl;
const迭代器
const string s2("hello world");
	string::const_iterator it4 = s2.begin();  //只读
	while (it4!=s2.end())
	{
		cout << *it4 << " ";
		++it4;
	}
	cout << endl;范围for (底层就是迭代器)
	for (auto e : s3)
	{
		cout << e << "";
	}
	cout << endl;
//底层就是迭代器,对迭代器的封装7. string类对象的容量操作
 
 capacity扩容机制
  
//查看扩容机制
void TestPushBack()
{
	string s;
	size_t sz = s.capacity();
	cout << "capacity changed: " << sz << '\n';
	cout << "making s grow:\n";
	for (int i = 0; i < 100; ++i)
	{
		s.push_back('c');
		if (sz != s.capacity())
		{
			sz = s.capacity();
			cout << "capacity changed: " << sz << '\n';
		}
	}
} 
我们能看到第一次是二倍,后续都是1.5扩容,在后面我们会进行讲
 相同的代码我们在liunx中能看到是二倍扩容
缩容

对数据进行缩容:默认缩容到15
注意:
8. string类对象的修改操作
void test_string5()
{
	//string s5("tast.txt");
	string s5("tast.txts.zip");
	//拿到文件后缀
	//size_t pos=s5.find('.');
	size_t pos = s5.rfind('.');
	if (pos != string::npos)
	{
		string suffixs = s5.substr(pos);
		cout << suffixs << endl;
	}
	cout << endl;
}void test_string4()
{
//拿到字符串中的指定数据xxx进行替换
	string s("hello world xxx");
	s.insert(0, "xx");
	cout << s << endl;
	s.erase(0, 2);
	cout << s << endl;
	string s1("hello world xxx");
	//s1.replace(12,3,"aaa");
	size_t pos = s1.find('x');
	while(pos != string::npos)
	{
		s1.replace(pos, 1, "a");
		pos = s1.find("x");  
	}
	cout << s1 << endl;
}注意
9. string类非成员函数
上面的几个接口大家了解一下,string类中还有一些其他的 操作,这里不一一列举,大家在需要用到时不明白了查文档即可。下一篇我们模拟实现string










