|
-
January 26th, 2003, 08:11 PM
#1
STL, find / replace all occurences of a substring in a string
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.
-
January 26th, 2003, 09:16 PM
#2
-
January 26th, 2003, 09:47 PM
#3
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
-
January 26th, 2003, 10:10 PM
#4
Well...I am not aware of any 'ReplaceAll' algorithm...therefore the following will do the trick...
Code:
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();
}
}
-
January 26th, 2003, 10:31 PM
#5
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. (
Last edited by TheBeginner; January 26th, 2003 at 10:36 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|