Posted By

mwb1100 on 01/10/11


Tagged


Versions (?)

string_replace()


 / Published in: C++
 

  1. //#define UNITTEST
  2.  
  3. #include <string>
  4.  
  5. using std::string;
  6.  
  7. string string_replace( string src, string const& target, string const& repl)
  8. {
  9. // handle error situations/trivial cases
  10.  
  11. if (target.length() == 0) {
  12. // searching for a match to the empty string will result in
  13. // an infinite loop
  14. // it might make sense to throw an exception for this case
  15. return src;
  16. }
  17.  
  18. if (src.length() == 0) {
  19. return src; // nothing to match against
  20. }
  21.  
  22. for (size_t idx = src.find( target); idx != string::npos; idx = src.find( target, idx)) {
  23. src.replace( idx, target.length(), repl);
  24. idx += repl.length();
  25. }
  26.  
  27. return src;
  28. }
  29.  
  30. #ifdef UNITTEST
  31.  
  32. #include <iostream>
  33. using std::cout;
  34. using std::endl;
  35.  
  36. void test( string s, string const& t, string const& r, string const& expected)
  37. {
  38. string result = string_replace( s, t, r);
  39.  
  40. if (result != expected) {
  41. cout << "ERROR: string_replace( \"" << s << "\", \"" << t << "\", \"" << r << "\") == \"" << result << "\", expected: \"" << expected << "\"" << endl;
  42. }
  43. }
  44.  
  45.  
  46. int main()
  47. {
  48. test( "", "", "", "");
  49. test( "a", "a", "b", "b");
  50. test( "cabcab", "cab", "xyz", "xyzxyz");
  51. test( "", "x", "y", "");
  52. test( "ababababa", "ba", "", "a");
  53. test( "cabcabcab", "cab", "cabcab", "cabcabcabcabcabcab");
  54. }
  55. #endif

Report this snippet  

You need to login to post a comment.