kkxx
kkxx

Reputation: 571

replace a substring of a given string in c++

I have a code to replace the content of a sub-string of a given string. It does not work as I expected.

From my understanding, s3.find("they") would return 6. Since pos is not the same as string::npos, then, from position 6, 2 characters in s3 are replaced by string s4. So, s3 would be "There boey go again!" after the replacement. Yet, the output of s3 is, "There Bob and Bill go again!". Could anyone help to explain?

#include <iostream>
#include <string>
using namespace std;
string prompt("Enter a line of text: "),
line( 50, '*');

int main()
  {

    string s3("There they go again!"),
           s4("Bob and Bill");
    int pos = s3.find("they");
    if( pos != string::npos )
        s3.replace(pos, 2, s4);
    cout << s3 << endl;
    cout << s4 << endl;
    return 0;
}

Upvotes: 2

Views: 1944

Answers (1)

Blaze
Blaze

Reputation: 16876

Yet, the output of s3 is, "There Bob and Bill go again!". Could anyone help to explain?

Not quite. The output is "There Bob and Billey go again". Starting from the word they it took the first two characters (th) and replaced them with Bob and Bill. The result is There Bob and Billey go again!.

This behavior is consistent with this documentation's explanation of std::string::replace:

Replaces the portion of the string that begins at character pos and spans len characters (or the part of the string in the range between [i1,i2)) by new contents:

(1) string Copies str.

If you wanted your output to be "There Boey go again!", you can do it like this:

int size = 2; // amount of characters that should be replaced
if (pos != string::npos)
    s3.replace(pos, size, s4.substr(0, size));

Upvotes: 2

Related Questions