-6

How can I parse a string given by a user and swap all occurrences of the old substring with the new string. I have a function to work with but I am really uncertain when it comes to strings.

void spliceSwap( char* inputStr, const char* oldStr, const char* newStr  )
CyberGuy
  • 2,783
  • 1
  • 21
  • 31
Nick
  • 1,036
  • 2
  • 14
  • 27

2 Answers2

2

The simplest solution is to use google (First link) here. Also be aware that in C++ we prefer std::string over const char *. Do not write your own std::string, use the built-in one. Your code seems to be more C than C++!

Community
  • 1
  • 1
CyberGuy
  • 2,783
  • 1
  • 21
  • 31
0
// Zammbi's variable names will help answer your  question   
// params find and replace cannot be NULL
void FindAndReplace( std::string& source, const char* find, const char* replace )
{
   // ASSERT(find != NULL);
   // ASSERT(replace != NULL);
   size_t findLen = strlen(find);
   size_t replaceLen = strlen(replace);
   size_t pos = 0;

   // search for the next occurrence of find within source
   while ((pos = source.find(find, pos)) != std::string::npos)
   {
      // replace the found string with the replacement
      source.replace( pos, findLen, replace );

      // the next line keeps you from searching your replace string, 
      // so your could replace "hello" with "hello world" 
      // and not have it blow chunks.
      pos += replaceLen; 
   }
}
Pierre Fourgeaud
  • 14,290
  • 1
  • 38
  • 62