简单的字符串替换给出错误,尽管参数正确

Simple string replace giving error despite correct arguments

本文关键字:参数 错误 字符串 替换 出错 简单      更新时间:2023-10-16

我正在尝试使用以下代码使用此处给出的详细信息替换字符串的一部分:

#include <iostream>
#include <string>
using namespace std ; 
int main(){
string ori = "this is a test"; // to replace "is a" with "IS A"
string part = "is a"; 
int posn = ori.find(part); 
int len = part.size(); 
cout << posn << endl; 
ori.replace(posn, len, ori, "IS A"); 
cout << ori; 
}

但是,它给出一个很长的错误,开头为:

rnreplacestr.cpp:11:36: error: no matching function for call to ‘std::__cxx11::basic_string<char>::replace(int&, int&, std::__cxx11::string&, const char [5])’
ori.replace(posn, len, ori, "IS A");
^
In file included from /usr/include/c++/6/string:52:0,
from /usr/include/c++/6/bits/locale_classes.h:40,
from /usr/include/c++/6/bits/ios_base.h:41,
from /usr/include/c++/6/ios:42,
from /usr/include/c++/6/ostream:38,
from /usr/include/c++/6/iostream:39,
from rnreplacestr.cpp:1:

问题出在哪里,如何解决?感谢您的帮助。

错误消息非常正确 - 没有匹配函数。我想你的意思是使用 std::string::replace 的三参数版本。

改变

ori.replace(posn, len, ori, "IS A"); 

ori.replace(posn, len, "IS A"); 

字符串替换只有 3 个参数而不是 4 个参数。请参阅文档 http://www.cplusplus.com/reference/string/string/replace/

您的生产线

ori.replace(posn, len, ori, "IS A"); 

应该是

ori.replace(posn, len, "IS A");