/ Published in: C++
Expand |
Embed | Plain Text
//#define UNITTEST #include <string> using std::string; string string_replace( string src, string const& target, string const& repl) { // handle error situations/trivial cases if (target.length() == 0) { // searching for a match to the empty string will result in // an infinite loop // it might make sense to throw an exception for this case return src; } if (src.length() == 0) { return src; // nothing to match against } for (size_t idx = src.find( target); idx != string::npos; idx = src.find( target, idx)) { src.replace( idx, target.length(), repl); idx += repl.length(); } return src; } #ifdef UNITTEST #include <iostream> using std::cout; using std::endl; void test( string s, string const& t, string const& r, string const& expected) { string result = string_replace( s, t, r); if (result != expected) { cout << "ERROR: string_replace( \"" << s << "\", \"" << t << "\", \"" << r << "\") == \"" << result << "\", expected: \"" << expected << "\"" << endl; } } int main() { test( "", "", "", ""); test( "a", "a", "b", "b"); test( "cabcab", "cab", "xyz", "xyzxyz"); test( "", "x", "y", ""); test( "ababababa", "ba", "", "a"); test( "cabcabcab", "cab", "cabcab", "cabcabcabcabcabcab"); } #endif
You need to login to post a comment.
