"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 + +