STL中string容器的用法

87 阅读1分钟

string的概念介绍

string是C++风格的字符串,而string本质上是一个类

string与char 的区别:

char* 是一个一级指针

而string是一个类,类的内部封装了char* 来管理这个字符串,是一个char* 类型的容器

特点

string类内部封装了很多成员的方法

例如:查找find,拷贝copy,删除delete等

可用string来管理char* 所分配的内存,不用担心复制越界与越界取值等

string构造函数

using namespace std;
#include <string>
void tese01()
{
	string s1;//默认构造

	const char* str = "hello world";
	string s2(str);
	cout << "s2=" << s2 << endl;//输出“hello world"
	
	string s3(10, 'a');
	cout << "s3=" << s3 << endl;//输出10个a

}

int main()
{
	tese01();
}

string字符存取

string中单个字符存取方式有2种

1.通过[]的方式取字符

2.通过at方式取字符

using namespace std;
#include <string>

void test01()
{
	string str = "hello world";

	//通过[]来访问单个字符
	for (int i = 0; i < str.size(); i++)
	{
		cout << str[i] << "";
	}
	cout << endl;

	//通过at来访问单个字符
	for (int i = 0; i < str.size(); i++)
	{
		cout << str.at(i) << endl;
	}

	//修改单个字符
	str[0] = 'x';
	cout << "str=" << str <<endl;
}

int main()
{
	test01();
	return 0;
}

这样我们就完成了对字符的存取

string中的插入和删除


删除字符串:string& insert

如:#include <iostream>
#include <string>
using namespace std;
void test01()
{
	string str = "hello";
	str.insert(1, "111");
	cout << str << endl;

	str.erase(1, 3);//从1号位置开始3个字符
	cout << str << endl;
}

int main()
{
	test01();
}

插入与删除的起始下标都从0开始

希望以上内容能对读者们有所帮助