
string我们之前使用过,如给类的属性定为字符串就要include<string>,是C++风格的字符串,c风格的字符串是个char*指针,而string是个类,内部封装了char*,用于管理字符串。内部封装了很多方法,而且管理内部的内存,不用担心赋值越界和取值越界的问题,由类内部负责,比如析构堆空间释放等等
构造方法
string(); 创建空字符串
string(const char* c); c语言字符串构造字符串
string(const string& s); 拷贝构造,用已有字符串创建
string(int n,char c);用n个字符c拼成的字符串

如上,我们可以看到几种使用方法,其中拷贝复制是直接使用赋值,本身等同于拷贝构造调用
赋值操作

string支持的赋值操作,除了重载了等号的内容几种赋值方法,还有使用成员函数assign方法进行赋值

如上,我们先示范=赋值操作,默认使用""包裹的字符串就是char*对待,之前的构造方法那里描述有误,使用拷贝构造或者=const string &s,这里是s2,s3是使用单个字符给字符串赋值,即当前字符串长度为1,我们需要注意不能使用String s = 'a';这种操作,会报错,需要先定义再赋值

如上,我们可以看到本质是一行初始化是在调用构造方法而非赋值。

如上,我们先声明,然后=赋值,才算赋值,否则会到构造函数列表里去找。

如上,我们使用assign方法,第一个就是传入c字符串没什么说的,第二个是给字符串的前几个字符拷贝,第三个是拷贝构造类似,最后一个是和重复字符的构造一样,我们都给实现了一圈
字符串拼接

我们可以使用重载+=操作符,也可以使用append操作符,原理类似,实现拼接

我们先实现+=操作,很简单,没什么说的,注意第二个是使用加单个字符,第三个不想额外定义string了,所以直接+=自己,实现2个重复内容

如上,我们调用了append方法,共有4种重载,1,3是传入字符串和自身,没什么说的,而2,4都是将字符串的指定长度传进来拼接,注意append没有和char直接的append操作

当然,也可以将字符串,从起始位置3开始加3个字符,如上第四个调用
字符串查找和替换

可以看到查找分为find,rfind方法,替换使用replace方法,其中,find是从左往右找,rfind是从右往左找,查找返回的都是Int型,即索引,字符串初始位置默认为0

如上,因为方法重载比较多,我们验证几个典型的,如上,我们可以看到4,7都有char o,虽然是第5,8个字符串,因为从0开始数,返回6,7

find默认其实位置是0,如果ins位置超过第一个o,就只能找到7

如果没有找到,会返回-1,注意我们要使用==-1做判断,我们直接输出可能是4294967295这个鬼东西,实际上他就是2的32次幂-1,32因为是4字节*8byte,记录的是-1的补码转换成的数字,我们判断==-1还是为true的

如上,我们看到replace方法的2个重载都是从start位置开始,n长度的内容替换成内容,我们就只用c格式char*字符串来实现替换,注意n长度并不会限制新字符串的替换。比如后面的字符串比较长,不会出现截断,就是完整替换过去
字符串比较
字符串比较实用compare函数,相同0,大于1,小于-1


简单调用如上,没什么好说的,就是ascii码的比较,如果首字母相同则,比较后面的字符,知道一个没有或者比出大小
判断大小的意义一般不大,常用于判断是否相等,当然也有按字典序排序这种操作
字符存取

首先,字符串是封装了c类型,支持使用索引来操作的,其次还可以使用内置方法at获得

如上,我们这里还使用了字符串的ength()方法获得字符串长度,注意不是属性,可以实现遍历每个字符

如上,我们当然还可以使用自带的size()方法获取到长度,因为char是1字节,就是按字节遍历,同时使用at方法获得字符

我们还可以通过制定index来修改字符,如上,修改了首字符的位置

当然,我们不能给其修改成字符串,类型不匹配。而且你看到字符串长度好像是3,其实还有个\0的结束符,使用sizeof和size获取的大小差1
插入和删除

如上,我们插入有insert方法,删除有erase方法,可以直接插入c风格字符串(之前说的双引号包裹的),以及字符串对象,以及n个重复的字符char,要指定起始位置,插入核心就是确定起始位置,传入字符串

接下来演示删除

如上,erase传入的参数分别是起始index和删除的长度
获取子串

如上方法就是substr,通过给定起始位置和长度获得

如上,功能是很简单

我们可以结合之前讲的find方法来实现将邮箱拆分出姓名的逻辑
网友评论