c++ - std::replace 有困难

标签 c++ string stl replace

我对 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::stringstd::basic_string<char>Tchar .

例如:

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/

相关文章:

c++ - VS2010 中的正向/强枚举

java - 将整数转换为字符串的问题

python - 克服字符串不可变性的 "disadvantages"

c++ - 我可以让 std::list 按顺序插入新元素吗?或者必须使用 std::sort?

c++ - 在模块之间传递 STL 和/或 MFC 对象

c++ - 无法在 C++ 中创建模板<typename T> vector<T>::iterator

c++ - Android NDK 与谷歌测试

c++ - 如何对 Mandelbrot 集执行简单缩放

c++ - 如何检查用户是否按下了 Edit 控件中的某个键

java - Java 中的字符串连接 - 何时使用 +、StringBuilder 和 concat