A friend of mine asked me how to replace a string with some other string in stl. How hard can it be? I immediately got a bad feeling in the stomack, remembering struggeling with this problem myself before. It's hard to try to persuade people to use stl when such simple matters don't have a clean solution with stl. I finally found something similar to this in a usenet post. It's about as clean as I can come up with. Any ideas?
[cpp]
#include "string"
#include "algorithm"
#include "iostream"
/*****************************************************************************/
static void Replace( std::string& source,
const std::string& find,
const std::string& replacement)
{
size_t len = find.length();
std::string::size_type pos = 0;
while( (pos = source.find( find, pos )) != std::string::npos )
{
source.replace( pos, len, replacement );
}
}
int main()
{
std::string Source =
"I once_had a dog named Harry and a dog named Noodles";
std::string FindStr = "dog";
std::string ReplaceStr = "cat";
std::cout < < Source < < std::endl;
Replace( Source, FindStr, ReplaceStr);
std::cout < < Source < < std::endl;
return 0;
}
[/cpp]