【C++心愿便利店】No.11---C++之string语法指南

文章目录


前言

👧个人主页:@小沈YO.

😚小编介绍:欢迎来到我的乱七八糟小星球🌝

📋专栏:C++ 心愿便利店

🔑本章内容:string

记得 评论📝 +点赞👍 +收藏😽 +关注💞哦~


提示:以下是本篇文章正文内容,下面案例可供参考

一、 为什么学习string类

C语言中,字符串是以'\0'结尾的一些字符的集合,为了操作方便,C标准库中提供了一些str系列的库函数,但是这些库函数与字符串是分离开的,不太符合OOP的思想,而且底层空间需要用户自己管理,稍不留神可能还会越界访问
开始学习string就需要开始学习读文档具体可以通过cplusplus.con网站去搜索

二、标准库中的string类

🌟string
1 . string类的了解:

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

总结:

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

在使用string类时,必须包含#include头文件以及using namespace std;
2 . string类的常用接口说明:
1 .string类对象的常见构造

(constructor)函数名称 功能说明
string() (重点) 构造空的string类对象,即空字符串
string(const char* s) (重点) 用C-string来构造string类对象
string(size_t n, char c) string类对象中包含n个字符c
string(const string&s) (重点) 拷贝构造函数
  • string() (重点) - - - 构造空的string类对象,即空字符串
cpp 复制代码
void test_string1()
{
	string s1;
	cout<<s1<<endl;
}
int main()
{
	test_string1();
	return 0;
}
  • string(const char* s) (重点)- - - 用C-string来构造string类对象
cpp 复制代码
void test_string1()
{
	string s2("hello");
	cout << s2 << endl;
}
int main()
{
	test_string1();
	return 0;
}
  • string(size_t n, char c) string类对象中包含n个字符c
cpp 复制代码
int main()
{
	string s1(3, 'a');
	cout << s1 << endl;
	return 0;
}
  • string(const string&s) (重点) 拷贝构造函数
cpp 复制代码
int main()
{
	string s1("hello");
	string s2(s1);
	cout << s1 << endl;
	cout << s2 << endl;
	return 0;
}

2 . string类对象的容量操作

函数名称 功能说明
size(重点) 返回字符串有效字符长度
length 返回字符串有效字符长度
capacity 返回空间总大小
empty (重点) 检测字符串释放为空串,是返回true,否则返回false
clear (重点) 清空有效字符
reserve (重点) 为字符串预留空间(确定大概知道要多少空间,提前开好,减少扩容,提高效率)
resize (重点) 将有效字符的个数改成n个,多出的空间用字符c填充
shrink_to_fit 将capacity容量缩至合适
  • size(重点)- - - 返回字符串有效字符长度
cpp 复制代码
int main()
{
	string s1("hello");
	string s2("aaaaaaaaaaaa");
	cout << s1.size() << endl;
	cout << s2.size() << endl;
	return 0;
}
  • length - - - 返回字符串有效字符长度
cpp 复制代码
int main()
{
	string s1("hello");
	string s2("aaaaaaaaaaaa");
	cout << s1.length() << endl;
	cout << s2.length() << endl;
	return 0;
}
  • capacity - - - 返回空间总大小
cpp 复制代码
int main()
{
	string s1("hello");
	string s2("aaaaaaaaaaaa");
	cout << s1.capacity () << endl;
	cout << s2.capacity ()<< endl;
	return 0;
}

同一个string对象,在不同平台下的capacity()(空间容量)可能不同,因为string在底层就是一个存储字符的动态顺序表,空间不够了要进行扩容,而不同平台底层的扩容机制有所不同,导致了最终capacity()的结果不同。例如下述展现的扩容机制:
🌟VS下的扩容机制: 第一次扩容是2倍,后面都是以1.5倍的大小去扩容。

cpp 复制代码
void test_string1()
{
	string s;
	size_t old = s.capacity();
	cout << "初始" << s.capacity() << endl;
	for (size_t i = 0; i < 100; i++)
	{
		s.push_back('a');
		if (s.capacity() != old)
		{
			cout << "扩容:" << s.capacity() << endl;
			old = s.capacity();
		}
	}
	cout << s.capacity() << endl;
}


🌟Linux下的扩容机制: 一次按照2倍的大小进行扩容

cpp 复制代码
void test_string1()
{
	string s;
	size_t old = s.capacity();
	cout << "初始" << s.capacity() << endl;
	for (size_t i = 0; i < 100; i++)
	{
		s.push_back('a');
		if (s.capacity() != old)
		{
			cout << "扩容:" << s.capacity() << endl;
			old = s.capacity();
		}
	}
	cout << s.capacity() << endl;
}
  • empty (重点)- - - 检测字符串释放为空串,是返回true,否则返回false
cpp 复制代码
int main()
{
	string s1;
	if (s1.empty())
	{
		cout << "s1是一个空字符串" << endl;
	}
	return 0;
}
  • clear (重点)- - - 清空有效字符
cpp 复制代码
void test_string8()
{
	string s1("hello world");
	cout << s1.size() << endl;//11
	cout << s1.capacity() << endl;//15
	s1.clear();
	cout << s1.size() << endl;//0
	cout << s1.capacity() << endl;//15
}
  • reserve (重点)- - - 为字符串预留空间(确定大概知道要多少空间,提前开好,减少扩容,提高效率)
cpp 复制代码
void test_string1()
{
	string s;
	s.reserve(100);
	size_t old = s.capacity();
	cout << "初始" << s.capacity() << endl;
	for (size_t i = 0; i < 100; i++)
	{
		s.push_back('a');
		if (s.capacity() != old)
		{
			cout << "扩容:" << s.capacity() << endl;
			old = s.capacity();
		}
	}
	s.reserve(10);
	cout << s.capacity() << endl;
}

如上当不写s.reserve(100);就会发生扩容,但是当写上s.reserve(100);提前开好空间就不会发生扩容,同时要注意s.reserve(10);并不会缩减空间(缩容)

  • resize (重点)- - - 将有效字符的个数改成n个,多出的空间用字符c填充
cpp 复制代码
void 	test_string2()
{
	string s1("hello world");
	cout << s1 << endl;
	cout << s1.size() << endl;
	cout << s1.capacity() << endl;

	//s1.resize(13, 'x');
	
	s1.resize(20, 'x');//这里有效字符个数改成20s1本来的有效字符hello world是11个超出部分用x补充,其次size()和capacity也会随之发生改变--->size()变成20;capacity()变成31
	
	s1.resize(5);
	cout << s1 << endl;
	cout << s1.size() << endl;
	cout << s1.capacity() << endl;

	string s2;
	s2.resize(10, '#');
	cout << s2 << endl;
	cout << s2.size() << endl;
	cout << s2.capacity() << endl;
}
  • shrink_to_fit() - - - 将capacity容量缩至合适
cpp 复制代码
void test_string1()
{
	string s;
	s.reserve(50);
	s += "hello world";
	cout << s.size() << endl;
	cout << s.capacity() << endl;
	s.shrink_to_fit();
	cout << s.size() << endl;
	cout << s.capacity() << endl;
}

注意:

  • size()与length()方法底层实现原理完全相同,引入size()的原因是为了与其他容器的接口保持一致,一般情况下基本都是用size()。
  • clear()只是将string中有效字符清空不改变底层空间大小
  • resize(size_t n) 与 resize(size_t n, char c)都是将字符串中有效字符个数改变到n个,不同的是当字符个数增多时:resize(n)用0来填充多出的元素空间,resize(size_t n, char c)用字符c来填充多出的元素空间 。注意:resize在改变元素个数时,如果是将元素个数增多,可能会改变底层容量的大小,如果是将元素个数减少,底层空间总大小不变。
  • 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的新遍历方式
  • operator[] (重点) 返回pos位置的字符,const string类对象调用
cpp 复制代码
void test_string2()
{
	string s1("hello world\n");
	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;;
}
  • begin+ end - - - begin获取一个字符的迭代器 + end获取最后一个字符下一个位置的迭代器
cpp 复制代码
void test_string3()
{
	string s4="hello world";
	string::iterator it = s4.begin();
	while (it != s4.end())
	{
		//读
		cout << *it << " ";
		it++;
	}
	cout << endl;
	it = s4.begin();
	//while (it < s4.end())可以这样写但是不建议
	while (it != s4.end())
	{
		//写
		*it='a';
		cout << *it << " ";
		it++;
	}
	cout << endl;
}
  • rbegin + rend - - - begin获取一个字符的迭代器 + end获取最后一个字符下一个位置的迭代器
cpp 复制代码
void test_string4()
{
	string s5 = "hello world";
	string::reverse_iterator rit = s5.rbegin();
	while (rit != s5.rend())
	{
		cout << *rit << " ";
		++rit;
	}
	cout << endl;
}
  • 范围for - - - C++11支持更简洁的范围for的新遍历方式
cpp 复制代码
void 	test_string5()
{
	string s6 = "hello world";
	//原理:编译器替换成迭代器
	for (auto ch : s6)
	{
		//读
		cout << ch << " ";
	}
	cout << endl;
	//对于写---范围for 本质自动遍历是*it赋值给ch,ch是*it的拷贝所以要写的话要加&,这样ch就是*it的别名
	for (auto ch : s6)//错误写法
	for (auto& ch : s6)
	{
		//写
		ch++;
	}
	cout << s6 << " ";
	cout << endl;

}
cpp 复制代码
void func(const string s)//不推荐传值传参,会进行拷贝调用拷贝构造string的底层不能用浅拷贝所以用引用+const

void func(const string& s)
{
	//迭代器支持读写,但是这里是const不支持迭代器写所以C++设计出了cbegin() cend() crbegin() crend()也可以+const例如下面一行注释代码
	//string::const_iterator it = s.begin();

	//对比于上面代码+const和不+const还用修改可以直接使用auto直接推出类型
	auto it = s.begin();
	while (it != s.end())
	{
		//读
		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_string6()
{
	string s7 = "hello world";
	func(s7);
}

4 . string类对象的修改操作

函数名称 功能说明
push_back 在字符串后尾插字符c
append 在字符串后追加一个字符串
operator+= (重点) 在字符串后追加字符串str
c_str(重点) 返回C格式字符串
find + npos(重点) 从字符串pos位置开始往后找字符c,返回该字符在字符串中的位置
rfind 从字符串pos位置开始往前找字符c,返回该字符在字符串中的位置
substr 在str中从pos位置开始,截取n个字符,然后将其返回
  • push_back - - - 在字符串后尾插字符c
cpp 复制代码
void test_string3()
{
	string s;
	string ss("hello");
	s.push_back('#');
	cout <<s<< endl;
}
  • append - - - 在字符串后追加一个字符串
cpp 复制代码
void test_string3()
{
	string s;
	string ss("hello");
	s.append("hello world");
	s.append(ss);
	cout <<s<< endl;
}
  • operator+= (重点) - - - 在字符串后追加字符串str
cpp 复制代码
void test_string3()
{
	string s;
	string ss("hello");
	s += '#';
	s += "hello";
	s += ss;
	cout << s << endl;
}
  • c_str(重点) - - - 返回C格式字符串
cpp 复制代码
void test_string9()
{
	string filename;
	cin >> filename;
	FILE* fout = fopen(filename.c_str(), "r");
}
  • find + npos(重点) - - - 从字符串pos位置开始往后找字符c,返回该字符在字符串中的位置
cpp 复制代码
void test_string2()
{
	string s1("test.cpp");//读取文件后缀
	size_t i = s1.find('.');
	string s3 = s1.substr(i);
	cout << s3 << endl;
}
  • rfind - - - 从字符串pos位置开始往前找字符c,返回该字符在字符串中的位置
cpp 复制代码
void test_string2()
{
	string s2("test.cpp.tar.zip");//找文件后缀.zip
	size_t j = s2.rfind('.');//倒着找
	string s4 = s2.substr(j);
	cout << s4 << endl;
}
  • substr - - - 在str中从pos位置开始,截取n个字符,然后将其返回
cpp 复制代码
void test_string2()
{
	string s1("test.cpp");//读取文件后缀
	size_t i = s1.find('.');
	string s3 = s1.substr(i);
	cout << s3 << endl;
}

注意:

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

5 . string类非成员函数

函数 功能说明
operator+ 尽量少用,因为传值返回,导致深拷贝效率低
operator>> (重点) 输入运算符重载
operator<< (重点) 输出运算符重载
getline (重点) 获取一行字符串
relational operators (重点) 大小比较
  • operator+ - - - 尽量少用,因为传值返回,导致深拷贝效率低
cpp 复制代码
void test_string3()//at失败后会抛异常
{
	string ss("hello");
	string ret=ss + '#';//+是一个传值返回,代价比较大
	string ret2 = ss + "hello";
	cout << ret << endl;
	cout << ret2 << endl;
	cout << endl;
}
  • operator>> (重点)- - - 输入运算符重载
  • operator<< (重点) - - - 输出运算符重载
  • getline (重点) - - - 获取一行字符串

🌟cin>> 和getline的区别在于:>>遇到空格' '和换行\n会截止,而getline默认只有遇到换行\n才截止,因此当我们需要从键盘读取一个含有空格的字符串是,只能用getline

cpp 复制代码
void test_string3()
{
	string s1;
	getline(cin, s1, '!');
	cout << s1;
}
  • relational operators (重点)- - - 大小比较

6 . string类类型转换接口

  • string类型转换成内置类型

  • 内置类型转换成string

  1. vs和g++下string结构的说明

注意:下述结构是在32位平台下进行验证,32位平台下指针占4个字节
vs下string的结构

string总共占28个字节,内部结构稍微复杂一点,先是有一个联合体,联合体用来定义string中字

符串的存储空间:

当字符串长度小于16时,使用内部固定的字符数组来存放

当字符串长度大于等于16时,从堆上开辟空间

cpp 复制代码
union _Bxty
{ // storage for small buffer or pointer to larger one
 value_type _Buf[_BUF_SIZE];
 pointer _Ptr;
 char _Alias[_BUF_SIZE]; // to permit aliasing
} _Bx;

这种设计也是有一定道理的,大多数情况下字符串的长度都小于16,那string对象创建好之后,内部已经有了16个字符数组的固定空间,不需要通过堆创建,效率高。

其次:还有一个size_t字段保存字符串长度,一个size_t字段保存从堆上开辟空间总的容量

最后:还有一个指针做一些其他事情。

故总共占16+4+4+4=28个字节

g++下string的结构

G++下,string是通过写时拷贝实现的,string对象总共占4个字节,内部只包含了一个指针,该指

针将来指向一块堆空间,内部包含了如下字段:

  • 空间总大小
  • 字符串有效长度
  • 引用计数
cpp 复制代码
struct _Rep_base
{
 size_type _M_length;
 size_type _M_capacity;
 _Atomic_word _M_refcount;
};
  • 指向堆空间的指针,用来存储字符串。

相关推荐
everyStudy41 分钟前
JS中判断字符串中是否包含指定字符
开发语言·前端·javascript
luthane43 分钟前
python 实现average mean平均数算法
开发语言·python·算法
Ylucius1 小时前
动态语言? 静态语言? ------区别何在?java,js,c,c++,python分给是静态or动态语言?
java·c语言·javascript·c++·python·学习
凡人的AI工具箱1 小时前
AI教你学Python 第11天 : 局部变量与全局变量
开发语言·人工智能·后端·python
sleP4o1 小时前
Python操作MySQL
开发语言·python·mysql
是店小二呀1 小时前
【C++】C++ STL探索:Priority Queue与仿函数的深入解析
开发语言·c++·后端
洛寒瑜1 小时前
【读书笔记-《30天自制操作系统》-23】Day24
开发语言·汇编·笔记·操作系统·应用程序
ephemerals__1 小时前
【c++】动态内存管理
开发语言·c++
咩咩觉主1 小时前
en造数据结构与算法C# 群组行为优化 和 头鸟控制
开发语言·c#
CVer儿1 小时前
条件编译代码记录
开发语言·c++