Can I replace a single character in a string with 2 characters?

Viewed 87
#include <algorithm>
#include <string>

void foo(std::string &s) {
    replace(s.begin(), s.end(), 'S', 'TH');
}

I want foo(s) to replace each S in s with the two characters TH. For example

std::string s = "SAT";
foo(s);
std::cout << s << "\n" // THAT

However, the definition of foo gives me an error.

Error (active) E0304 no instance of function template "std::replace" matches the argument list

Why does this not work?

1 Answers

std::replace cannot do it, but you can use std::regex_replace instead.

#include <regex>

std::string s = "SAT";
s = regex_replace(s, std::regex("S"), "TH");
std::cout << s << "\n"; // output: THAT
Related