加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – std :: replace难度大

发布时间:2020-12-16 10:24:25 所属栏目:百科 来源:网络整理
导读:我还是STL的新手,想用k替换字符串中所有出现的ch. 我尝试了以下方法: std::replace (str.begin(),str.end(),"ch","k"); 但它抛出了这个错误: no matching function for call to ‘replace(__gnu_cxx::__normal_iteratorchar*,std::basic_stringchar,std::c
我还是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*,const char [2],const char [1])

在这种情况下如何让替换工作?

注意:我看到了一个类似的问题但在这种情况下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(),'c','k');

要解决您的问题,请阅读:How do I replace all instances of a string with another string?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读