zoukankan      html  css  js  c++  java
  • 删除字符串指定字母或者字符串

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

      

     

    不一样的烟火
  • 相关阅读:
    asp.net的decimal保留两位小数
    由于管理员设置的策略,该磁盘处于脱机状态-Win 2008 R2
    论大公司的通病和缺点
    sql server删除数据后空间无变化处理方法
    sql server压缩数据库和日志文件
    SQL千万级数据设计和优化
    SQL Server索引怎么用
    在电脑上测试手机网站
    asp.net实现GZip压缩和GZip解压
    WebService教程和分析
  • 原文地址:https://www.cnblogs.com/cstdio1/p/11217735.html
Copyright © 2011-2022 走看看