string介绍
1.string是表示字符串的字符串类
2.该类的接口与常规容器的接口基本相同,再添加了一些专门用来操作string的常规操作。
3.string在底层实际是:basic_string模板类的别名,typedef basic_string string;
4.不能操作多字节或者变长字符的序列。
5.在使用string类时,必须包含#include头文件以及using namespace std;
string类查询网站:http://www.cplusplus.com
官网:https://en.cppreference.com/w/
string类的常用操作
在使用string时要包含#include头文件以及using namespace std;
给string的对象赋值
java
string 对象名1;//空对象
#给string的对象赋值
string 对象名2("值");
string 对象名3(string对象名);
string 对象名4(数值, '字符');
string 对象名5 = "值";
string 对象名6 = 对象名;
具体用法如下:

给string对象插入值
java
#调用push.back()函数实现尾插单个字符
#调用append()函数实现尾插字符串
#使用+=可在字符串末尾插入单个字符,也可以尾插字符串
具体举例如下:

将字符串转为整形
遍历每个字符逐一转换,每个字符减去'0'转成其对应的数值。

string中四个默认成员函数
| 函数名称 | 功能 |
|---|---|
| string() | 构造空的string类对象,即空字符串 |
| string(const char* s) | 用C-string来构造string类对象 |
| string(size_t n, char c) | string类对象中包含n个字符c |
| string(const string& s) | 拷贝构造 |

遍历字符串

指针遍历字符串

str与str.c_str的区别
string str:C++ 字符串类,自带长度,不受\0截断,可直接增删改字符串。
str.c_str():返回const char*(C 语言字符串指针),靠\0判断结尾

使用迭代器遍历字符串


倒着遍历


计算字符串长度

capacity和clear的使用

扩容:一般以1.5倍数扩容,具体情况具体分析

reserve预分配足够的空间

扩容时直接填入某个值,可以使用resize,但是再插入其他值时是在值的后面插入,如下图:在插入100个a时还要进行两次扩容

使用resize指定已有字符串长度时,如果指定值比字符串长度小,会缩短字符串
如下图:原来字符串是右边这样的

执行完s.resize(5);之后就变成如下图这样子了,字符串长度变为5.

如果再插入其他值的话,只能在其后面插入,如下图所示

指定位置插入与删除

find()与rfind()的使用
java
string::find(pos, start)
str.find(ch):从下标 0开始,查找字符第一次出现位置,返回下标
str.find(ch, n):从下标 n开始向后查找
找不到返回常量 string::npos
string::substr(start, len)
substr(a, b):从下标 a 截取长度 b的字符串
substr(a):从下标 a 一直截取到字符串末尾
java
//find()与rfind()的使用
//int main() {
// string s1("test.cpp");
// string s2("work.txt");
// string s3("test.c");
// size_t pos1 = s1.find('.');
// if (pos1 != string::npos) {
// cout << s1.substr(pos1) << endl;//.cpp
// }
// size_t pos2 = s2.find('.');
// if (pos2 != string::npos) {
// cout << s2.substr(pos2) << endl;//.txt
// }
// size_t pos3 = s3.find('.');
// if (pos3 != string::npos) {
// cout << s3.substr(pos3) << endl;//.c
// }
// string s4("hello.cpp.gz");//从最后一个点开始找
// size_t pos4 = s4.rfind('.');
// if (pos4 != string::npos) {
// cout << s4.substr(pos4) << endl;//.gz
// }
//}
//find()的应用
//网址:协议 域名 资源名称
//string biturl(https://www.doubao.com/chat/38425040872563970);
//分离
void split_url(const string& str) {
size_t i1 = str.find(':');
if (i1 != string::npos) {
cout << str.substr(0, i1) << endl;//https
}
//找第三个\下标
size_t i2 = str.find('/', i1+3);
if (i2 != string::npos) {
cout << str.substr(i1 + 3, i2 - (i1 + 3)) << endl;//www.doubao.com
}
cout << str.substr(i2 + 1) << endl;//chat/38425040872563970
}
//int main() {
// string biturl("https://www.doubao.com/chat/38425040872563970");
// split_url(biturl);
// return 0;
//}