c++基础-string常见操作

1.获取长度(length())

string str = "12345";
int l = str.length();//长度为5

2.拼接(+)

string str1 = "hello";
string str2 = "world";
str1 = str1 + " " + str2;//str1="hello world"

3.添加(append)

//尾部追加
 
string str1 = "hello";
string str2 = "world";
str1.append(" " + str2);//str1="hello world"

4.插入(insert)

string str = "hello world";
string str2 = "hard ";
string str3 = "it is so happy wow";
 
//s.insert(pos,n,ch)        在字符串s的pos位置上面插入n个字符ch
str.insert(6,4,'z');        // str = "hello zzzzworld"
 
//s.insert(pos,str)         在字符串s的pos位置插入字符串str
str.insert(6,str2);         // str = "hello hard world"
 
//s.insert(pos,str,a,n)     在字符串s的pos位置插入字符串str中位置a到后面的n个字符
str.insert(6,str3,6,9);     // str = "hello so happy world"
 
//s.insert(pos,cstr,n)      在字符串s的pos位置插入字符数组cstr从开始到后面的n个字符
//此处不可将"it is so happy wow"替换为str3
str.insert(6,"it is so happy wow",6);       // str = "hello it is world"

5.删除(erase)

//erase(index,n)从下标index开始删除n个字符
string str = "01234567";
str.erase(3, 2);//str="012567"

6.剪切(substr)

string tmp;
调用substr的字符串不改变
//①substr(index,n)从下标index开始截取n个字符
string str1 = "0123456789";
tmp=str1.substr(6, 2);//tmp="67"  str1 = "0123456789"
//②substr(index)从下标index开始截取字符至字符串结束
string str2 = "0123456789";
tmp=str2.substr(7);//tmp="789"    str2 = "0123456789"

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值