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


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

 

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM