gpt4 book ai didi

c++ - std::replace 有困难

转载 作者:太空狗 更新时间:2023-10-29 19:46:10 24 4
gpt4 key购买 nike

我对 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com