C++示例讲解string容器

2022-11-13 11:11:58 示例 容器 讲解

string基本概念

本质:

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

string和char*区别

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

特点:

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

例如: 查找find,拷贝copy,删除delete、替换replace、插入 insert

string管理char*所分配的内存,不用担心复制越界和取值越界等,由内部类进行负责

string初始化

#include<string>

void test01()
{
	string s1; //默认构造
	const char* str = "hello world";
	string s2(str);
	cout << s2 << endl;
	//方法3,拷贝构造
	string s3(s2);
	cout << "s3 = " << s3 << endl;
	//方法4
	string s4(10,'a');
}

string赋值操作


void test01()
{
	//方法1
	string str1;
	str1 = "hello world";
	cout << "str1 =" << str1 << endl;
	//方法2
	string str2;
	str2 = str1;
	cout << "str2 =" << str2 << endl;
	//方法3
	string str3;
	str3 = 'a';
	cout << "str3 =" << str3 << endl;
	//方法4
	string str4;
	str4.assign("hello c++");
	cout << "str4 =" << str4 << endl;
	//方法5
	string str5;
	str5.assign(str4, 5);
	cout << "str5 =" << str5 << endl;
	//方法6
	string str6;
	str6.assign(str5);
	cout << "str6 =" << str6 << endl;
	//方法7
	string str7;
	str7.assign(10,'w');
	cout << "str7 =" << str7 << endl;
}

string字符串拼接


void test02()
{
	//方法1
	string str2_1 = "my ";
	str2_1 += "love play game";
	cout << "str2_1 =" << str2_1 << endl;
	//方法2
	str2_1 += 't';
	cout << "str2_1 =" << str2_1 << endl;
	//方法3
	string str2_2;
	str2_2.assign("I LOVE LEARN and ");
	str2_2 += str2_1;
	cout << "str2_2 =" << str2_2 << endl;
	//方法4
	string str2_3;
	str2_3 = "I";
	str2_3.append(" Love");
	cout << "str2_3 =" << str2_3 << endl;
	//方法5
	string str2_4 = "aaa";
	str2_4.append("bcd", 2);
	cout << "str2_4 =" << str2_4 << endl;
	//方法6
	string str2_5 = "bbb";
	str2_5.append(str2_4,0,2);
	cout << "str2_1 =" << str2_5 << endl;
}

到此这篇关于C++示例讲解string容器 的文章就介绍到这了,更多相关C++ string容器 内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关文章