ofey ofey - 1 month ago 4x
C++ Question

Difficulty with std::replace

I am still new to STL and wanted to replace all occurrences of

in a string with

I tried the following:

std::replace (str.begin(), str.end(), "ch", "k");

But it threw this error:

no matching function for call to ‘replace(__gnu_cxx::__normal_iterator<char*,
std::basic_string<char, std::char_traits<char>, std::allocator<char> > >,
__gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>,
std::allocator<char> > >, const char [2], const char [1])

How do I get
to work in this case?

Note: I saw a similar question but in that case the OP was using "blah" and 'b' as arguments to be replaced but here both of my arguments are strings.


Since the definition of std::replace is

template< class It, class T >
void replace( It first, It last, const T& old_value, const T& new_value );

Reference http://en.cppreference.com/w/cpp/algorithm/replace

You must pass a char because a std::string is std::basic_string<char> and T is a char.

For example:

std::replace (str.begin(), str.end(), 'c',  'k');

To solve your problem, read: How do I replace all instances of a string with another string?