CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Jan 2003
    Posts
    3

    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.

  2. #2
    Join Date
    Dec 2002
    Posts
    287

  3. #3
    Join Date
    Jan 2003
    Posts
    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

  4. #4
    Join Date
    May 2000
    Location
    KY, USA
    Posts
    18,652
    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();
      }
    }

  5. #5
    Join Date
    Jan 2003
    Posts
    3
    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
  •  





Click Here to Expand Forum to Full Width

Featured