C++ string用法总结

string

1、头文件

#include<string>

2、初始化

string s{"hello world"};
string s1{6,'z'};//zzzzzz
string s2{s};
string s3{"hello world",5};//hello
string s4{"hello world",7,5};//world,开始位置,字符个数

3、添加

//添加子串
string s5=s+s;//hello worldhello world
string s6=s+"hello world";//hello worldhello world
//不能 s6="hello"+"hello",两个字面意义上的字符串不能相加

4、删除

s.erase(0,6);//world,开始索引,删除字符个数
s.clear();//清除

5、截取

string s7=s.substr(7,5);//world,从第7位截取5个字符
string s8=s.substr(5);//hello

6、搜索

int index=s.find("world");//6
int index2=s.find('h');//0
index2=s.find('z');
if (index2 == string::npos)//判断不存在
{
	cout << "no" << endl;
}
s.rfind('o')//7,逆向搜索

7、插入

s.insert(11,"hello world");//插入开始位置,插入开始位置可以是字符串最后一位的后一位

8、替换

s.replace(6,5,"me");//hello me.将从6开始的之后5个字符替换成me

9、char类型与string

s2 =s+ 'a' + 'b';
string s9{ 'c' };
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值