How to find and replace string?

Replace first match

Use a combination of std::string::find and std::string::replace.

Find the first match:

std::string s;
std::string toReplace("text to replace");
size_t pos = s.find(toReplace);

Replace the first match:

s.replace(pos, toReplace.length(), "new text");

A simple function for your convenience:

void replace_first(
    std::string& s,
    std::string const& toReplace,
    std::string const& replaceWith
) {
    std::size_t pos = s.find(toReplace);
    if (pos == std::string::npos) return;
    s.replace(pos, toReplace.length(), replaceWith);
}

Usage:

replace_first(s, "text to replace", "new text");

Demo.


Replace all matches

Define this O(n) method using std::ostringstream as a buffer:

void replace_all(
    std::string& s,
    std::string const& toReplace,
    std::string const& replaceWith
) {
    std::ostringstream oss;
    std::size_t pos = 0;
    std::size_t prevPos = pos;

    while (true) {
        prevPos = pos;
        pos = s.find(toReplace, pos);
        if (pos == std::string::npos)
            break;
        oss << s.substr(prevPos, pos - prevPos);
        oss << replaceWith;
        pos += toReplace.size();
    }

    oss << s.substr(prevPos);
    s = oss.str();
}

Usage:

replace_all(s, "text to replace", "new text");

Demo.


Boost

Alternatively, use boost::algorithm::replace_all:

#include <boost/algorithm/string.hpp>
using boost::replace_all;

Usage:

replace_all(s, "text to replace", "new text");

Leave a Comment