Replace function
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: Replace function

  1. #1
    Join Date
    Dec 2005
    Posts
    382

    Replace function

    The goal is to replace Invalid_Enum with int. The approach.

    Code:
    
    # include <string>
    # include <iostream>
    
    void 
    Replace( std::string& Source, const std::string& Replacement) 
    {   
      std::string::size_type Pos = 0;
      Pos = Source.find( '(' ); Pos++;
      std::string::size_type Pos2 = 0;
      Pos2 = Source.find ( "Enum" , Pos ) ;  Pos2 += 3;
      Source.replace ( Pos, Pos2, Replacement );
     
    } 
    
    
    int main() {
    
      std::string test ( "(Invalid_Enum e )" ) 
      Replace ( test, " int" ) ;
      std::cout << test << std::endl;
      std::cin.get();
    }
    I'm not sure there's a more efficient way to do this? I suspect one way to do this is to write the replace function to take as arguments the Source string, the Replacement strings, the start and end character (or start and end string) .

  2. #2
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,263

    Re: Replace function

    Quote Originally Posted by mop65715
    The goal is to replace Invalid_Enum with int.
    Taking what you say literally, it sounds like you want to write:
    Code:
    #include <string>
    #include <iostream>
    
    void Replace(std::string& subject, const std::string& search, const std::string& replacement)
    {
        std::string::size_type pos = subject.find(search);
        if (pos != std::string::npos)
        {
            std::string::iterator begin = subject.begin() + pos;
            subject.replace(begin, begin + search.size(), replacement);
        }
    }
    
    int main()
    {
        std::string test("(Invalid_Enum e )");
        Replace(test, "Invalid_Enum", " int");
        std::cout << test << std::endl;
        std::cin.get();
    }
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center