string to replace all of the specified string (C ++) [Reserved]

Reprinted from https://blog.csdn.net/a_222850215/article/details/79985504

 

C ++ provides the string replace method to achieve the replacement string, but for the entire string in a string replace this function, string and did not realize that we do today is this.
First, understand the concept that replaces all string, the "12212" this string of all "12" are replaced by "21", what is the result?
It may be 22211, 21221 can also be a different scene sometimes applications, will want to get a different result, so the answer to these two have done to achieve, the following code:

   #include   <string>     
    #include   <iostream>     
    using   namespace   std;     
    string&   replace_all(string&   str,const   string&   old_value,const   string&   new_value)     
    {     
        while(true)   {     
            string::size_type   pos(0);     
            if(   (pos=str.find(old_value))!=string::npos   )     
                str.replace(pos,old_value.length(),new_value);     
            else   break;     
        }     
        return   str;     
    }     
    string&   replace_all_distinct(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;     
    }     
    int   main()     
    {     
        cout   <<   replace_all(string("12212"),"12","21")   <<   endl;     
        cout   <<   replace_all_distinct(string("12212"),"12","21")   <<   endl;     
    }     
    /* 
    输出如下:    
    22211    
    21221 
    */  

OK, so, the task is complete it.
In fact, it may often write on this blog some of these small programs puzzled, but I always feel that some seemingly insignificant things, often at a critical time, affect your performance or efficiency, huh, huh, after all, want to be useful La.

 

Guess you like

Origin www.cnblogs.com/nxopen2018/p/11697952.html