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

      

     

    不一样的烟火
  • 相关阅读:
    (转)jQuery.extend 函数详解
    (转)跟我一起学JQuery插件开发教程
    (转)jQuery插件开发全解析
    (转)弹出窗口lhgDialog API文档
    (转)反射发送实战(-)InvokeMember
    (转)JQuery处理json与ajax返回JSON实例
    linux下添加用户并赋予root权限
    Linux 下配置,安装Hadoop
    Linux 下安装 jdk-7u79-linux-x64.gz,jdk1.7.0_79,jdk1.7步骤:
    linux下导入、导出mysql数据库命令
  • 原文地址:https://www.cnblogs.com/cstdio1/p/11217735.html
Copyright © 2011-2022 走看看