Strings In Depth13 / 15
Up next

Replace all

#include <print>
#include <string>

std::string replace_all(std::string s, std::string_view from, std::string_view to) {
    std::size_t pos = 0;
    // walk forward, replacing each match in place
    while ((pos = s.find(from, pos)) != std::string::npos) {
        s.replace(pos, from.size(), to);
        pos += to.size();
    }
    return s;
}

int main() {
    std::println("{}", replace_all("a-b-c", "-", "_"));
}
What you're solving

swap every occurrence of a substring