#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;
}