zoukankan      html  css  js  c++  java
  • string替换所有指定字符串(C++)

    C++的string提供了replace方法来实现字符串的替换,但是对于将字符串中某个字符串全部替换这个功能,string并没有实现,我们今天来做的就是这件事。
    首先明白一个概念,即string替换所有字符串,将"12212"这个字符串的所有"12"都替换成"21",结果是什么?
    可以是22211,也可以是21221,有时候应用的场景不同,就会希望得到不同的结果,所以这两种答案都做了实现,代码如下:

    #include<iostream>
    #include<vector>
    #include<list>
    #include<string>
    #include<cmath>
    #include<algorithm>
    using namespace std;
    #define debug
    /**************替换空格*******************************************/
    string& replace_all(string& str,const string& old_value,const string& new_value)
    {
        while(true)
        {
            int pos=0;
            if((pos=str.find(old_value,0))!=string::npos)
                str.replace(pos,old_value.length(),new_value);
            else break;
        }
        return str;
    }
    string& repalce_all_ditinct(string& str,const string&old_value,const string& new_value)
    {
        for(string::size_type pos(0);pos!=string::npos;pos+=new_value.length())
        {
            if((pos=str.find(old_value,pos))!=string::npos)
                str.replace(pos,old_value.length(),new_value);
            else break;
        }
        return str;
    }
    string& repalce_all_my(string& str,const string&old_value,const string& new_value)
    {
        for(int pos=0;pos!=-1;pos+=new_value.length())
            if((pos=str.find(old_value,pos))!=-1)
                str.replace(pos,old_value.length(),new_value);
            else break;
        return str;
    }
    int main()
    {
        string str="12212";
        cout<<repalce_all_ditinct(str,"12","21")<<endl;
        str="12212";
        cout<<replace_all(str,"12","21")<<endl;
        str="12212";
        cout<<repalce_all_my(str,"12","21")<<endl;
        return 0;
    }
    1. 输出如下:
    2. 22211
    3. 21221
    4. */

    OK,这样的话,任务就完成啦。

  • 相关阅读:
    STM32 printf 方法重定向到串口UART
    STM32F401CCU6与MFRC522接线及读取示例
    Keil MDK5 STM32F401CCU6开发环境配置
    Keil MDK5 STM32F103C8T6开发环境配置
    RFID EPC Class1 Gen2电子标签笔记
    Ubuntu20.04下的ESP8266环境
    Centos7使用memtester测试内存
    内核5.4以上, Realtek 8111网卡初始化失败
    Centos7的KVM安装配置详解
    Python抓取网页例子
  • 原文地址:https://www.cnblogs.com/seurain/p/3277037.html
Copyright © 2011-2022 走看看