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]
Threw this together for a school assignment.. so useful. Still, very Q&D :3
[cpp]std::string whip::str_replace(std::string search, std::string replace, std::string subject)
{
int pos = subject.find(search, 0);
while(pos != -1)
{
subject.erase(pos, search.length());
subject.insert(pos, replace);
pos = subject.find(search, pos + replace.length());
}
return subject;
}[/cpp]
Just because you gave me the chance, may I please correct the code to the following:
[cpp]
std::string whip::str_replace(const std::string& search, const std::string& replace, const std::string& subject)
{
int pos = subject.find(search, 0);
while(pos != std::string::npos)
{
subject.erase(pos, search.length());
subject.insert(pos, replace);
pos = subject.find(search, pos + replace.length());
}
return subject;
}
[/cpp]
:3