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 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();
}
}
?
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;
}
}