Essays | Replacement string subroutine for C + +

Source: Internet
Author: User

"C + + Primer" an exercise, I wrote when I encountered a few small problems, record:

1, I think std::string::replace can only equal length string equivalent substitution (influenced by the C language string style), the fact that the old string and the new string is completely inconsistent length.

2. The first simple version can actually replace success when written out, but there is a problem with a dead loop. For example, if there is "knife" in the source string, we need to replace "K" with "KC" and we will get into a dead loop. Because I'm using find to find the string, and not set the start to find the location.

Finally write the code for debugging success.

std::string replace (const std::string& _text, const std::string& _old_replace, const std::string& _NEW_ Replace) {std::string output = _text;std::size_t Last_pos = 0;do{if ((Last_pos = Output.find (_old_replace, last_pos))! = St D::string::npos) {output.replace (Last_pos, _old_replace.length (), _new_replace.c_str ()); Last_pos + = _new_ Replace.length ();}} while (last_pos! = std::string::npos); return output;}

  

Essays | Replacement string subroutine for C + +

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.