C++ String replaces the specified string

  • 2020-05-27 06:51:52
  • OfStack

An example of String replacing a specified string in C++

C++ 's string provides the replace method for string substitution, but string does not implement the ability to replace a string in its entirety. That's what we're going to do today.

First of all, understand the concept of string replacing all strings, replacing all "12" of the string "12212" with "21". What is the result?

It could be 22211, it could be 21221. Sometimes you want different results depending on the application scenario, so both of these answers are implemented.

The code is as follows:


#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;   
}   
/* 
 The output is as follows :  
22211  
21221 
*/ 

OK, so that's the job done.

In fact, you may not understand this blog often write some small procedures, but I always feel that some seemingly insignificant things, often in the critical moment, affect your efficiency or performance,

If you have any questions, please leave a message or come to the site community to exchange discussion, thank you for reading, hope to help you, thank you for your support of the site!


Related articles: