C++ String的进阶操作II

前边说的都是string类的构造函数
下面这些是用于string操作的库函数

substr()//主要功能是复制子字符串,要求从指定位置开始,并具有指定的长度。
append() //方法在被选元素的结尾(仍然在内部)插入指定内容。提示:如需在被选元素的开头插入内容,请使用prepend()方法。
replace()//该函数返回一个字符串,其中指定的字符串已经被替换为另一字符串,并且替换的次数也可以指定。

代码实例:

#include <iostream>
#include <string>

using namespace std;
//20200425 测试字符串操作  公众号:C与C语言plus

int main()
{
  string s("Hello world");
  string s2 = s.substr(6,5);  //从第6个开始取5个
  cout << s2 << endl ;        //s2为world

  s2 = s.substr(6);  //从第6个开始取复制所有的
  cout << s2 << endl ;        //s2为world

  s2 = s.substr(6);    //s2复制s,相当于s2=s
  cout << s2 << endl ;  //s2为Hello world

  s = "C++ Primer";
  s.append(" 3rd Ed");   //再s最后添加3rd Ed
  cout << s<< endl ;  //s为C++ Primer 3rd Ed

  s = "C++ Primer";
  s.insert(s.size()," 3rd Ed"); //最后插入
  cout << s<< endl ;  //s为C++ Primer 3rd Ed

  s.replace(11,3,"4th");       //下标11开始3个替换4th
    cout << s<< endl ;  //s为C++ Primer 4th Ed

  s.replace(11,3,"Fourth");       //下标11开始3个替换Fourth
    cout << s<< endl ;  //s为C++ Primer Fourth Ed

  s = "C++ Primer 3rd Ed";    //replace相当于先删除后插入
  s.erase (11,3);            //删除3rd
  s.insert(11,"Fourth");      //插入Fourth
  cout << s<< endl ;  //s为C++ Primer Fourth Ed

  return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值