我对 STL 还是个新手,想用 k
替换字符串中所有出现的 ch
。
我尝试了以下方法:
std::replace (str.begin(), str.end(), "ch", "k");
但是它抛出了这个错误:
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])
如何让 replace
在这种情况下工作?
注意:我看到了一个类似的问题,但在那种情况下,OP 使用“blah”和“b”作为要替换的参数,但这里我的两个参数都是字符串。
最佳答案
自 std::replace
的定义|是
template< class It, class T >
void replace( It first, It last, const T& old_value, const T& new_value );
引用 http://en.cppreference.com/w/cpp/algorithm/replace
您必须传递 char
因为 std::string
是std::basic_string<char>
和 T
是 char
.
例如:
std::replace (str.begin(), str.end(), 'c', 'k');
要解决您的问题,请阅读:How do I replace all instances of a string with another string?
关于c++ - std::replace 有困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16762339/