Click to See Complete Forum and Search --> : STL, find / replace all occurences of a substring in a string


TheBeginner
January 26th, 2003, 07:11 PM
Sorry for stupid question, but...

The problem is as follows. For two given std::strings s1 and s2 I must find all occurences of s2 in s1 and replace them with, say, s3 (C++,STL). Of course, there's a number of different solutions of the problem. But I do want to find solution that can be expressed "in one string", using a combination of some usual STL algorithms, without explicit "find-replace" cycle.

I tried hard but I can't invent it by myself. I remember that I have already seen such a thing somewhere oin the net, but I can't found it in any way. So, I'm just going insane. Help me, please.

DanM
January 26th, 2003, 08:16 PM
basic_string::replace

http://msdn.microsoft.com/library/en-us/vcstdlib/html/vclrf_string_Basicstringreplace.asp?frame=true

Dan

TheBeginner
January 26th, 2003, 08:47 PM
Thanks, but I'm aware of basic_string members :)
The problem is how to fit it with standard library algorithms to perform "replace all" without a cycle

Andreas Masur
January 26th, 2003, 09:10 PM
Well...I am not aware of any 'ReplaceAll' algorithm...therefore the following will do the trick...

void ReplaceSubstring(std::string *const cpstrSource,
const std::string &refcstrSearch,
const std::string &refcstrReplace)
{
std::string::size_type pos = 0;

while((pos = cpstrSource->find(refcstrSearch, pos)) != std::string::npos)
{
cpstrSource->replace(pos, refcstrSearch.length(), refcstrReplace);
pos += refcstrReplace.length();
}
}

TheBeginner
January 26th, 2003, 09:31 PM
Thank you. This is almost exactly the code I succeded to construct. But I saw another piece of code (in a tutorial) that did the same in one string, without a loop. But now I cannot find that tutorial and cannot remind how that code worked. :(((( And I feel really stupid. :((