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.

4
  • 2
    Please try to avoid using namespace std; because it is considered bad practice. See Why is “using namespace std;” considered bad practice? Commented Sep 27, 2019 at 8:36
  • Should I use std:: at all places? Commented Sep 27, 2019 at 8:38
  • Well, yes. It may seem cumbersome, but it increases readability and prevents subtle name lookup problems when the program gets complicated. Commented Sep 27, 2019 at 8:39
  • 3
    OK, instead of ori.replace(posn, len, ori, "IS A"); just do ori.replace(posn, len, "IS A"); Commented Sep 27, 2019 at 8:41

2 Answers 2

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"); 
Sign up to request clarification or add additional context in comments.

Comments

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.