C++ 字符串string类常用操作

目录

添加操作

1.+、+=

2.append()

3.push_back()

4.insert()

删除操作

1.erase()

2.pop_back()

3.clear()

修改操作

1.replace()

2.substr()

3.stoi()、stof()、to_string()

查找操作

1.at()

2.find()


添加操作

1.+、+=

string s1 = "abc";
string s2 = "def";
string s3;
s1 += s2;    // 将s2插入s1末尾
s3 = s1 + s2;    // 将s2插入s1末尾存入s3

2.append()

s.append("abc")    // 将"abc"加入s
s.append("abc", 2)    // 将"abc"从初始位置开始的前2个字符加入s,即"ab"加入s
s.append("abc", 1, 2);    // 将"abc"的[1, 2)区间加入s,即"a"加入s

3.push_back()

s.push_back('a');    // 在字符串s末尾插入一个a

4.insert()

s.insert(1, "abc");    // 从1位置开始插入字符串"def"
s.insert(s.begin() + 1, 2, 'a');    // 在1位置后插入2个字符a

删除操作

1.erase()

s.erase(1, 3);    // 删除字符串s区间[1, 3]的字符
s.erase(2);    // 删除字符串s从2位置开始之后的全部字符

2.pop_back()

s.pop_back();    // 从末尾弹出一个字符

3.clear()

s.clear();    // 清空字符串s

修改操作

1.replace()

s.replace(0, 2, "abc");    // 将s的[0, 2]区间修改为"abc"
s.replace(0, 1, "abc", 2);    // 将s的[0, 1]区间修改为"abc"前两个,即"ab"
s.replace(0, 1, "abc", 1, 2);    // 将s的[0, 1]区间修改为"abc"的[1, 2]区间,即"bc"

2.substr()

string s1 = s.substr(0, 2);    // 取s的[0, 2]区间存入s1
string s2 = s.substr(1);    // 取s的从1位置开始到末尾存入s2

3.stoi()、stof()、to_string()

string s = "123";
int s1 = stoi(s);    // 将s转换成整型数字
float s2 = stof(s);    // 将s转换成浮点型数字
string s3 = to_string(123)    // 将数字转换成字符串

查找操作

1.at()

char c = s.to(2);    // 查找字符串s的第2个字符

2.find()

string s = "abcabc";
int pos1 = s.find('b');    // 返回s中第一个'b'的位置,不存在则返回string::npos
int pos2 = s.find("bc");    // 返回s中第一个"bc"的初始位置,不存在则返回string::npos

// 判断s中是否存在"bc"子串
if(s.find("bc") != string::npos) cout << "Yes" << endl;
else cout << "No" << endl;

int pos3 = s.find("bc", 3);    // 从2位置开始找到第一个匹配字符串"bc"的位置,即pos3 = 4
int pos4 = s.find_first_of("bc");    // 从前往后找到第一个匹配字符串"bc"的位置,即pos4 = 1
int pos5 = s.find_first_not_of("bc");    // 从前往后找第一个不匹配字符串"bc"的位置,即pos5 = 0
int pos6 = s.find_last_of("bc");    // 从后往前找到第一个匹配字符串"bc"的位置,即pos6 = 4
int pos7 = s.find_last_not_of("bc")    // 从后往前找第一个不匹配字符串"bc"的位置,即pos7 = 3
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值