C + + string replace

Source: Internet
Author: User

The C + + string provides the Replace method to implement the replacement of the string, but the string does not implement the function of replacing a string in the string, which is what we're doing today. First we understand the concept that string replaces all strings, substituting "21" for all "12" of the "12212" string, and what the result is.

Can be 22211, can also be 21221, sometimes the application of different scenarios, you will want to get different results, so both of the answers are implemented, the code is as follows:


#include <</span>string>
#include <</span>iostream>
using namespace Std;
string& Replace_all (string& str,const string& old_value,const)
{
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)
{
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"), "a", "a" << Endl;
cout << replace_all_distinct (String ("12212"), "a", "a" << Endl;
}   

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.