C++字符串的插入、替换与删除的实现

 具体实现代码如下

#include <iostream>
#include <string>
#include <string.h>
using namespace std;
int main(void){
	string str1="We can insert a string";
	string str2="a str into ";
	
	//在字符串指定位置前面插入指定字符串
	cout <<str1.insert(14,str2)<<endl;
	
	//在字符串指定位置前面插入指定字符串的子串(从指定索引开始的指定个数的字符)
	cout <<str1.insert(14,str2,2,9)<<endl;
	
	//插入指定字符串的前n个字符
	cout <<str1.insert(14,"test hello",5)<<endl;
	
	//插入n个同样字符到字符串中
	cout <<str1.insert(14,6,'*')<<endl;
	
	//替换指定索引开始的指定长度的子串
	cout <<str1.replace(3,3,"may")<<endl;
	
	//用给定字符串的指定子串来进行替换
	//例如以下。实际上使用的是could来进行替换
    cout <<str1.replace(3,3,"can could",4,5)<<endl;
           
	//使用给定字符串的前n个字符来进行替换:can
	cout <<str1.replace(3,5,"can could",3)<<endl;
	
	//使用指定个数的反复字符来进行替换
	cout <<str1.replace(3,3,5,'*')<<endl;
	
	string word="We";
	size_t index=str1.find(word);
	if(index!=string::npos)
	//删除指定索引开始的指定长度的字符
	cout <<str1.erase(index,word.length())<<endl;
	return 0;
	
}

输出结果:

We can insert a str into a string
We can insert str into a str into a string
We can insert test str into a str into a string
We can insert ******test str into a str into a string
We may insert ******test str into a str into a string
We could insert ******test str into a str into a string
We can insert ******test str into a str into a string
We ***** insert ******test str into a str into a string
 ***** insert ******test str into a str into a string

 

原文出处:https://www.cnblogs.com/cxchanpin/p/6950399.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值