insert()函数与substr()函数

insert()函数:

insert ( pos, str2);——将字符串str2插入到原字符串下标为pos的字符前

insert (pos, n, c);——在将n个字符c插入到原字符串下标为pos的字符前

insert (pos, str2, pos1, n);——将st2r从下标为pos1开始数的n个字符插在原串下标为pos的字符前

语法:str1.insert(pos , str2); 等等

代码参考

#include<iostream>
#include<string>
using namespace std; int main()
{
//insert()函数
string str1 = "abef";
string s1 = "cd";
str1.insert(2,s1);
cout<<str1<<endl;//abcdef 在串str下标为2的e前插入字符串str2 str1.insert(2,5,'c');
cout<<str1<<endl;//abccccccdef 在串str1下标为2的e前插入5个字符'c' string str2="hello";
string s2="weakhaha";
str2.insert(0,s2,1,3);//将字符串s2从下标为1的e开始数3个字符,分别是eak,插入原串的下标为0的字符h前
cout<<str2<<endl; return 0;
}

substr()函数

主要功能是复制子字符串,要求从指定位置开始,并具有指定的长度。如果没有指定长度_Count或_Count+_Off超出了源字符串的长度,则子字符串将延续到源字符串的结尾也可以用于字符的插入拼接

语法:substr(size_type _Off = 0,size_type _Count = n)

​ substr(pos, n)

解释:pos - 从此位置开始拷贝

​ n - 拷贝长度为 n 的字符串(注意:n 是长度而不是下标)

代码参考:

#include<iostream>
#include<string>
using namespace std; int main()
{
string str1 = "abcg";
string str2 = "def"; // string类字符串可以直接进行连接
//从a开始 长度为3:(下标)+1 的字符串abc + def + g
string str3 = str1.substr(0,2+1) + str2 + str1.substr(2+1);
// 子串 子串
cout<<str3<<endl;//abcdefg return 0;
}

总结:

在前插入为insert,复制字串用strsub。两者均可用来实现字符串的插入操作

最新文章

  1. 解决PowerShell命令行窗口中不显示光标的问题
  2. jdbc实现事务
  3. C++设计模式——代理模式
  4. ios7.0结合storyborad实现页面跳转的总结
  5. 【HDU】1717 小数化分数2 ——计数原理
  6. Qt学习之路(24): QPainter(改写paintEvent)
  7. boost库之geometry
  8. RabbitMQ基础
  9. 如何安装Orchard
  10. PAT 1082. 射击比赛 (20)
  11. 【Swfit】Swift与OC两种语法写单例的区别
  12. Python面向对象基础知识
  13. Spring Boot 整合mybatis 使用多数据源
  14. MySQL 的主从原理和复制过程简述
  15. 存折打印机测量和毫米方式Form配置说明
  16. Sakila——MySQL样例数据库解析(已经迁移)
  17. linux文件管理 -&gt; 系统文件属性
  18. 雷林鹏分享:Ruby 范围(Range)
  19. 77. Combinations (Recursion)
  20. December 23rd 2016 Week 52nd Friday

热门文章

  1. Unity VideoPlayer视频模糊
  2. nginx负载均衡与反向代理
  3. 29、windows下通过zip包方式安装mysql
  4. FlowNet:simple / correlation 与 相关联操作
  5. 『心善渊』Selenium3.0基础 — 22、使用浏览器加载项配置实现用户免登陆
  6. SQL查询语句中参数带有中文查询不到结果
  7. python 正则表达式 中级
  8. mysql binlog恢复数据实战
  9. WPF技巧:命中测试在视觉树中的使用
  10. windows服务器下MySQL配置字符集