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
}
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
}
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.
Why not return a modified string?
If you need performance, here is an optimized function that modifies the input string, it does not create a copy of the string:
Tests:
Output:
The check for oldStr being empty is important. If for whatever reason that parameter is empty you will get stuck in an infinite loop.
But yeah use the tried and tested C++11 or Boost solution if you can.
I love boost library, and this is a test of boost library!
My templatized inline in-place find-and-replace:
It returns a count of the number of items substituted (for use if you want to successively run this, etc). To use it: