views:

657

answers:

3

Is there a way to replace all occurrences of a substring with another string in std::string?

For instance:

void SomeFunction(std::string& str)
{
   str = str.replace("hello", "world"); //< I'm looking for something nice like this
}
+3  A: 

The easiest way (offering something near what you wrote) is to use Boost.Regex, specifically regex_replace.

std::string has built in find() and replace() methods, but they are more cumbersome to work with as they require dealing with indices and string lengths.

Alan
There are also the boost string algorithms, including replace_all (regex might be a bit heavy-weight for such simple substitution).
UncleBens
+5  A: 

Why not implement your own

void myReplace(std::string& str, const std::string& old, const std::string& new)
{
  size_t pos = 0;
  while((pos = str.find(old, pos)) != std::string::npos)
  {
     str.replace(pos, old.length(), new);
     pos += new.length();
  }
}

?

yves Baumes
All good, except that `new` is a keyword ;)
Pavel Minaev
arghhh .. I should have seen that !!!! ;-)
yves Baumes
so why not edit your answer to fix it?
Evan Teran
It gives a sense to Pavel's question.
yves Baumes
A: 

I believe this would work

It takes const char*'s as a parameter.

//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( it, 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; 
   }
}
Adam Tegen
Given that `size_type` for a string is `unsigned`, your `>=` check in the loop condition will always be `true`. You have to use `std::string::npos` there.
Pavel Minaev
size_type is not unsigned. It's unsigned on many platforms, but not all.
Alan
Why in the world is this not part of std::string? Is there any other serious String class in the world of programming that does not offer a 'find and replace' operation? Surely it's more common than having two iterators and wanting to replace the text between them?? Sometimes std::string feels like a car with a tunable spectrum windshield but no way to roll down the driver's window.
Spike0xff