Tag Archives: Find and Replace

Find and replace in C++

The standard C++ string class has 39 member functions, but never the one you need. A find-and-replace function one of those that is missing. Fortunately it can easily be implemented in terms of the find() and replace() methods:

#include <string>
#include <iostream>
#include <climits>

std::string string_replace(const std::string& str, const std::string& match, 
        const std::string& replacement, unsigned int max_replacements = UINT_MAX)
    size_t pos = 0;
    std::string newstr = str;
    unsigned int replacements = 0;
    while ((pos = newstr.find(match, pos)) != std::string::npos
            && replacements < max_replacements)
         newstr.replace(pos, match.length(), replacement);
         pos += replacement.length();
    return newstr;

The Boost library has replace_all(), which does the replacement in-place, modifying the original string.

The pystring library has replace(), which not surprisingly works the same way as the Python string.replace() method.