In C++, the string::replace() method replaces a portion of a string by position and length, not by substring. Use find() to locate the substring first:
string result = sentence;
result.replace(result.find("cats"), 4, "dogs");
// find("cats") returns the starting index
// 4 is the length of "cats"
// "dogs" is the replacement
Here is an example:
string sentence = "I love cats";
string result = sentence;
result.replace(result.find("cats"), 4, "dogs");
cout << result; // "I love dogs"
Assignment
Follow the Coding Tutorial and replace "cats" with "dogs" in sentence!
Hint
Create result as a copy of sentence, then use result.replace(result.find("cats"), 4, "dogs").
Free plan: 30 tutor messages. PRO is unlimited.
Saved
Ctrl + Enter to check
