0

I am trying to replace part of a string using details given here with following code:

#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; 
}

However, it is giving a long error starting with:

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:

Where is the problem and how can it be solved? Thanks for your help.

rnso
  • 23,686
  • 25
  • 112
  • 234
  • 2
    Please try to avoid `using namespace std;` because it is considered bad practice. See [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/q/1452721) – L. F. Sep 27 '19 at 08:36
  • Should I use `std::` at all places? – rnso Sep 27 '19 at 08:38
  • Well, yes. It may seem cumbersome, but it increases readability and prevents subtle name lookup problems when the program gets complicated. – L. F. Sep 27 '19 at 08:39
  • 3
    OK, instead of `ori.replace(posn, len, ori, "IS A");` just do `ori.replace(posn, len, "IS A");` – L. F. Sep 27 '19 at 08:41

2 Answers2

8

The error message is quite right - there is no matching function. I think you meant to use the three-parameter version of std::string::replace.

Change

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

to

ori.replace(posn, len, "IS A"); 
acraig5075
  • 10,588
  • 3
  • 31
  • 50
4

String replace has only 3 arguments not 4. See documentation http://www.cplusplus.com/reference/string/string/replace/

Your line

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

should be

ori.replace(posn, len, "IS A");
1m2r3a
  • 76
  • 5