C++容器string

36 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第8天,点击查看活动详情

1、基本概念

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

与char*的区别:

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

特点:

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

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

string管理char*所分配的内存,不用担心赋值越界和取值越界等,有类内部负责。

2、string的构造函数

        string s1;//默认构造
	const char * str = "hello world";
	string s2(str);//拷贝构造
	cout << "s2:" << s2 << endl;
	string s3(s2);
	cout << "s3:" << s3 << endl;
	string s4(10, 'a');//构造一个字符串为十个a
	cout << "s4:" << s4 << endl;

3、string字符串拼接

第一种是用“+”加号拼接,第二种是使用函数append拼接。

string str1="hello";//追加字符串,追加字符
	str1 +='!';
	cout << "str1=" << str1 << endl;
	string str2 = "asasa";
	str1.append("ass",2);//追加字符串
	str1.append("1");//不能追加字符,只能追加字符串
	str1.append(str2,2,2);//第二个字符开始截取三个字符。

4、字符串获取

string uname = s1.substr(n, m);//截取n到m之间的字符串给新的字符串。

string str1 = "ssdadd";
	for (int i = 0; i < str1.size(); i++) {
		cout << str1[i] << " " << endl;
	}
	for (int i = 0; i < str1.size(); i++) {
		cout << str1.at(i) << " " << endl;
	}
	string s1 = "204997867@11.com";
	int pos = s1.find("@");
	cout << "pos" << pos << endl;
	string uname = s1.substr(0, pos);
	cout << "uname" << uname << endl;

5、字符串访问

有[],和at两种方式,类似于数组的访问形式,同时也可以对其修改。

string str1 = "ssdadd";
	for (int i = 0; i < str1.size(); i++) {
		cout << str1[i] << " " << endl;
	}
	for (int i = 0; i < str1.size(); i++) {
		cout << str1.at(i) << " " << endl;
	}

6、字符串比较

字符串比较的依据是Ascii码,逐个比较字符串的字符的ASCII值大小,若str1大于str2则返回1,等于则返回0,小于就返回-1.字符串比较的主要应用价值就在于字符串相等。

string str1 = "ss";
string str2 = "ss";
cout << str1.compare(str2) << endl;

image.png