Start learning free

LESSON 62 OF 667 · STRINGS I

String Replace in C++

Lesson

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

STEP 1 OF 1
    Ctrl + Enter to check