2

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; } 
4
  • Please edit your question and show us an example of input, actual output and expected output. Commented Oct 30, 2019 at 14:08
  • 1
    The output is There Bob and Billey go again!, since you replace two characters, starting at pos (i.e. the th in the original string) by the second string, Bob and Bill. Commented Oct 30, 2019 at 14:08
  • It behaves like cplusplus.com/reference/string/string/replace says it should not like you say it does. Commented Oct 30, 2019 at 14:08
  • string::find returns a std::string::size_type, not an int. int cannot even hold a string::npos. Commented Oct 30, 2019 at 14:12

1 Answer 1

2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.