删除字符串指定字母或者字符串

#include "iostream"
#include "cstring"
#include "string"
#include "algorithm"
#include "cmath"
#include "set" 
using namespace std;

int main()
{
string str;
cin>>str;
string tmp=str; 
int found=str.find("a");
while(found!=-1){//删除字符串指定字符 
str.erase(found,1);//删除单个字符,注意用str.replace(found,1,"")有bug 
found=str.find("a",0);//删除之后从0继续查找	
}
cout<<str<<endl; 

found=tmp.find("a");
while(found!=-1){//替换全部子串 
tmp.replace(found,1,"asd");//在字符串str中从found位置开始用字符串"asd"替换总长为1的字符串
found=tmp.find("a",found+1);
}

cout<<tmp<<endl; 
}

 运行效果图如下:

 删除指定字符串

#include "iostream"
#include "cstring"
#include "string"
#include "algorithm"
#include "cmath"
#include "set" 
using namespace std;

int main()
{
string str;
cin>>str;
string tmp=str; 
int found=str.find("asd");//asd是要删除的字符串 
while(found!=-1){//删除字符串指定字符或者字符串 
str.erase(found,3);//删除单个字符,注意用str.replace(found,1,"")有bug 
found=str.find("asd",found+1);//注意这里不能再从0开始查找(单个字母需要从再0开始),
//例如:aasdsd,从0开始str会变成空串(因为删除一次asd之后第一个a和sd会合并一个新的asd,从0开始会继续删除合成的asd),
//从found+1再搜索str之后会输出asd(不会删除合成的asd)	
}
cout<<str<<endl; 
}

 删除单个字符直接用erase不用配合find(直接自己判断就行)

#include "iostream"
#include "cstring"
#include "string"
#include "algorithm"
#include "cmath"
#include "set" 
using namespace std;

int main()
{
string str;
cin>>str;
for(int i=0;i<str.size();i++){
	if(str[i]=='a'){str.erase(i,1);i=-1;//i++之后i=0;继续从头搜索 
	} 
} 
cout<<str<<endl; 
}

  

 

转载于:https://www.cnblogs.com/cstdio1/p/11217735.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值