C++初阶—string类

第一章:为什么要学习string类

1.1 C语言中的字符串

C语言中,字符串是以'\0'结尾的一些字符的集合,为了操作方便,C标准库中提供了一些str系列的库函数,但是这些库函数与字符串是分离开的,不太符合OOP的思想,而且底层空间需要用户自己管理,稍不留神可能还会越界访问。

1.2 面试题

在OJ中,有关字符串的题目基本以string类的形式出现,而且在常规工作中,为了简单、方便、快捷,基本都使用string类,很少有人去使用C库中的字符串操作函数。

第二章:标准库中的string类

2.1 string类

  1. 字符串是表示字符序列的类
  2. 标准的字符串类提供了对此类对象的支持,其接口类似于标准字符容器的接口,但添加了专门用于操作单字节字符字符串的设计特性。
  3. string类是使用char(即作为它的字符类型,使用它的默认char_traits和分配器类型(关于模板的更多信息,请参阅basic_string)。
  4. string类是basic_string模板类的一个实例,它使用char来实例化basic_string模板类,并用char_traits和allocator作为basic_string的默认参数(根于更多的模板信息请参考basic_string)。
  5. 注意,这个类独立于所使用的编码来处理字节:如果用来处理多字节或变长字符(如UTF-8)的序列,这个类的所有成员(如长度或大小)以及它的迭代器,将仍然按照字节(而不是实际编码的字符)来操作。

总结:

  1. string是表示字符串的字符串类
  2. 该类的接口与常规容器的接口基本相同,再添加了一些专门用来操作string的常规操作。
  3. string在底层实际是:basic_string模板类的别名,typedef basic_string<char, char_traits, allocator> string;
  4. 不能操作多字节或者变长字符的序列。

在使用string类时,必须包含#include头文件以及using namespace std;

2.2 string类的常用接口说明

1. string类对象的常见构造

函数名称 功能说明
string() (重点) 构造空的string类对象,即空字符串
string(const char* s) (重点) 用C-string来构造string类对象
string(size_t n, char c) string类对象中包含n个字符c
string(const string&s) (重点) 拷贝构造函数

2. string类对象的容量操作

函数名称  功能说明
size(重点) 返回字符串有效字符长度
length 返回字符串有效字符长度
capacity 返回空间总大小
empty (重点) 检测字符串释放为空串,是返回true,否则返回false
clear (重点)  清空有效字符
reserve (重点) 为字符串预留空间**
resize (重点) 将有效字符的个数该成n个,多出的空间用字符c填充

注意:

  1. size()与length()方法底层实现原理完全相同,引入size()的原因是为了与其他容器的接口保持一致,一般情况下基本都是用size()。
  2. clear()只是将string中有效字符清空,不改变底层空间大小。
  3. resize(size_t n) 与 resize(size_t n, char c)都是将字符串中有效字符个数改变到n个,不同的是当字符个数增多时:resize(n)用0来填充多出的元素空间,resize(size_t n, char c)用字符c来填充多出的元素空间。注意:resize在改变元素个数时,如果是将元素个数增多,可能会改变底层容量的大小,如果是将元素个数减少,底层空间总大小不变。
  4. reserve(size_t res_arg=0):为string预留空间,不改变有效元素个数,当reserve的参数小于string的底层空间总大小时,reserver不会改变容量大小。

3. string类对象的访问及遍历操作

函数名称 功能说明
operator[] (重点) 返回pos位置的字符,const string类对象调用
begin+ end begin获取一个字符的迭代器 + end获取最后一个字符下一个位置的迭代器
rbegin + rend begin获取一个字符的迭代器 + end获取最后一个字符下一个位置的迭代器
范围for C++11支持更简洁的范围for的新遍历方式

4. string类对象的修改操作

函数名称 功能说明
push_back 在字符串后尾插字符c
append 在字符串后追加一个字符串
operator+= (重点) 在字符串后追加字符串str
c_str(重点) 返回C格式字符串
find + npos(重点) 从字符串pos位置开始往后找字符c,返回该字符在字符串中的位置
rfind 从字符串pos位置开始往前找字符c,返回该字符在字符串中的位置
substr 在str中从pos位置开始,截取n个字符,然后将其返回

注意:

  1. 在string尾部追加字符时,s.push_back(c) / s.append(1, c) / s += 'c'三种的实现方式差不多,一般情况下string类的+=操作用的比较多,+=操作不仅可以连接单个字符,还可以连接字符串。
  2. 对string操作时,如果能够大概预估到放多少字符,可以先通过reserve把空间预留好。

5. string类非成员函数

函数 功能说明
operator+ 尽量少用,因为传值返回,导致深拷贝效率低
operator>> (重点) 输入运算符重载
operator<< (重点) 输出运算符重载
getline (重点) 获取一行字符串
relational operators (重点) 大小比较

string类内部就是char*,为什么不直接用char*而是要封装成string类。

为了适应不同的编码(UTF-8、UTF-16、UTF-32等),从而表示不同国家的文字

接口示例

#include <iostream>
#include <string>
#include <list>
using namespace std;

void test_string1() {
	string s1;
	string s2("hello");

	//输入 输出
    //C++可以按需提取,C语言只能使用固定大小的数组
    //cin 会读取输入直到遇到第一个空格、制表符(Tab)、换行符等空白字符为止。
    //也就是说,它不会读取空格或换行之后的内容,只会读取直到空白字符之前的内容。
	cin >> s1;
	cout << s1 << endl;
	cout << s2 << endl;

	//拼接字符串
	//相比strcat,可读性更强;strcat空间不够,不能自动扩容;
	//strcat要先找\0,如果字符串较长,消耗时间
	string ret1 = s1 + s2;//s1+s1也可以,两个s1的内容拷贝到ret1(对象+对象)
	cout << ret1 << endl;

	string ret2 = s1 + "我来了";//对象+字符串
	cout << ret2 << endl;
}

void test_string2() {
	string s1("hello world");//直接调用构造函数
	string s2 = "hello world";//构造+拷贝构造+优化,本质是隐式类型转换(单参数构造函数支持隐式类型转换)

	//遍历string
	for (size_t i = 0; i < s1.size(); i++)
		cout << s1[i] << " ";//读
	cout << endl;

	for (size_t i = 0; i < s1.size(); i++)
		s1[i]++;//写
	cout << s1 << endl;//ifmmp!xpsme


	//遍历的第二种方式:迭代器
	string::iterator it = s1.begin();//iterator是在string这个类里面定义的,所以需要加string类域
	while (it != s1.end()) { //end指向最后一个有效字符的后一个位置,即\0
		cout << *it << " ";//读
		++it;
	}
	cout << endl;

	it = s1.begin();
	//while (it < s1.end()) //这里可以改为<,但不建议
	//因为迭代器是通用的,string空间是连续的,但其他数据结构不一定,比如list
	while (it != s1.end()) {
		*it = 'a';//写
		++it;
	}
	cout << s1 << endl;//aaaaaaaaaaa


	//链表示例
	list<int> lt;
	lt.push_back(1);
	lt.push_back(2);
	lt.push_back(3);
	lt.push_back(4);
	list<int>::iterator lit = lt.begin();
	while (lit != lt.end()) { //链表只能用!=,不能用<
		cout << *lit << " ";
		++lit;
	}
	cout << endl;
}

void test_string3() {
	string s1("hello world");

	//正向遍历
	string::iterator it = s1.begin();//iterator是在string这个类里面定义的,所以需要加string类域
	while (it != s1.end()) { //end指向最后一个有效字符的后一个位置,即\0
		cout << *it << " ";//读
		++it;
	}
	cout << endl;

	//反向遍历
	//string::reverse_iterator rit = s1.rbegin();
	auto rit = s1.rbegin();//rbegin的返回值就是反向迭代器,所以可以使用auto
	while (rit != s1.rend()) {
		cout << *rit << " ";//d l r o w   o l l e h
		++rit;//这里++是从后向前倒着走
	}
	cout << endl;

	//原理:编译时编译器替换成迭代器
	//读
	for (auto ch : s1) //范围for不支倒序遍历。如果想修改需要引用
		cout << ch << " ";
	cout << endl;

	//写
	for (auto& ch : s1)
		ch++;
	cout << s1 << endl;
}


//void func(string s) //不推荐传值传参,会调用拷贝构造
void func(const string& s) {
	//string::iterator it = s.begin();//迭代器支持读写,但参数有const修饰,所以报错
	//string::const_iterator it = s.begin();
	auto it = s.begin();
	while (it != s.end()) {
		//const迭代器不支持写
		//*it = 'a';

		cout << *it << " ";
		++it;
	}
	cout << endl;

	//string::const_reverse_iterator rit = s.rbegin();
	auto rit = s.rbegin();
	while (rit != s.rend()) {
		cout << *rit << " ";
		++rit;
	}
	cout << endl;
}

void test_string4() {
	string s1("hello worldxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
	func(s1);

	string s2(s1);//拷贝构造

	string s3(s1, 6, 5);//从下标6位置开始取5个字符  
	cout << s3 << endl;//world
	
	//npos 是一个静态成员常量值,无符号整形-1(即最大值),表示“直到字符串的末尾”。
	string s4(s1, 6);//从从下标6位置开始取到结束。最后一个是缺省参数npos
	cout << s4 << endl;

	//不使用缺省参数,也可以计算
	string s5(s1, 6, s1.size() - 6);//size是字符串长度
	cout << s5 << endl;

	string s6(10, 'a');//用10个a初始化
	cout << s6 << endl;

	string s7(++s6.begin(), --s6.end());//用迭代器区间初始化
	cout << s7 << endl;//aaaaaaaa

	//三种赋值方法
	string s8;
	s8 = s7;
	s8 = "xxx";
	s8 = 'y';
}

void test_string5() {
	string s1("hello world");
	cout << s1.size() << endl;//11 size具有通用性
	cout << s1.length() << endl;//11
	cout << s1.capacity() << endl;//15

	s1.clear();//仅清除数据,不释放空间
	cout << s1.size() << endl;//0
	cout << s1.capacity() << endl;//15

	//为什么结尾是\0
	//需要兼容C语言,而且有些场景只能调C的接口
	//文件示例
	string filename;
	cin >> filename;
	FILE* fout = fopen(filename.c_str(), "r");//fopen函数第一个参数是字符串
	//const char* c_str() const; 返回一个指向数组的指针,该数组包含以 null 结尾的字符序列(即 C 字符串),表示字符串对象的当前值。
}

void test_string6() {
	string s;
	size_t old = s.capacity();
	cout << "初始" << s.capacity() << endl;

	for (size_t i = 0; i < 100; i++) {
		s.push_back('x');

		if (s.capacity() != old) {
			cout << "扩容:" << s.capacity() << endl;
			old = s.capacity();
		}
	}
	//初始15
	//扩容:31
	//扩容:47
	//扩容:70
	//扩容:105


	string s1;
	//reserve价值,确定大概要多少空间,提前开辟,减少扩容,提高效率
	
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值