2
#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?

HTNW
  • 27,182
  • 1
  • 32
  • 60
lk911
  • 35
  • 2

1 Answers1

2

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
HTNW
  • 27,182
  • 1
  • 32
  • 60
aetrnm
  • 402
  • 3
  • 13
  • 1
    you don't need a regex, `std::string::replace` can do it – 463035818_is_not_an_ai Jul 30 '21 at 18:07
  • 1
    @463035818_is_not_a_number, tbh, I tried to find a solution with string::replace, but didn't manage. It's never late to post your answer in a comment, I am learning from mistakes too! – aetrnm Jul 30 '21 at 18:34
  • 1
    https://godbolt.org/z/1434nfTT5, though return value of `find` should be checked. I find strings memebr functions confusing too, because they have similar names as algorithms but work with indices rather than iterators, can be rather confusing – 463035818_is_not_an_ai Jul 30 '21 at 18:37