Programming: July 2006 Archives

Replace me!

| | Comments (2)
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]

About this Archive

This page is a archive of entries in the Programming category from July 2006.

Programming: February 2005 is the previous archive.

Find recent content on the main index or look in the archives to find all content.