Thiago R. Adams website

Home Code-Blog Projects Twitter Blog Links / Books About

Websites

Find-Replace for standard strings

I always need this function! It is self-explanation.

inline void find_replace(std::string& in_this_string,
                         const std::string& find,
                         const std::string& replace)
{
    std::string::size_type pos = 0;
    while( std::string::npos != (pos = in_this_string.find(find, pos)) )
    {
        in_this_string.replace(pos, find.length(), replace);
        pos += replace.length();
    }
}

inline void find_replace(std::wstring& in_this_string,
                         const std::wstring& find,
                         const std::wstring& replace)
{
    std::wstring::size_type pos = 0;
    while( std::wstring::npos != (pos = in_this_string.find(find, pos)) )
    {
        in_this_string.replace(pos, find.length(), replace);
        pos += replace.length();
    }
}

See also cmpnocase

Want to see more? Go to the CodeBlog section.

About the author: I am Thiago Adams. I work as a professional C++ software engineer. I have created this website to share ideas and source code with other people with similar interests.
I would like to hear from you comments, critics, questions and suggestions about this topic or any other part of this website. Email: thiago.adams at gmail dot com