Start learning free

LESSON 61 OF 343 · STRINGS I

String Replace in C++: replace() with find()

Lesson Read the full explanation

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

    C++ · STRINGS I

    String Replace in C++, explained

    How replace works in C++

    Many languages have a function that takes the text to look for and the text to put in its place. The C++ std::string member replace works differently. It replaces a range of positions: you tell it where the range starts, how many characters it covers, and what text goes in.

    s.replace(pos, len, newText);
    

    It removes len characters beginning at index pos, then inserts newText at that spot. The new text can be longer or shorter than the part it replaces. The string grows or shrinks to fit.

    string r = "I love cats";
    r.replace(7, 4, "elephants");   // "I love elephants"
    

    Here index 7 is the "c" of "cats" and 4 is the length of "cats", so exactly that word is swapped out.

    Changing the string in place

    replace modifies the string it is called on and does not make a new one. That is a difference from languages where strings cannot change. It returns a reference to the same string, but you rarely need the return value. If you want to keep the original, copy first:

    string sentence = "I love cats";
    string result = sentence;   // a separate copy
    

    Assigning one string to another copies the characters, so changing result later leaves sentence alone.

    Using find to locate the text

    Usually you know what to replace but not where it is. That is the job of find, which returns the index of the first match. Passing that straight to replace gives the pattern most C++ code uses:

    result.replace(result.find("cats"), 4, "dogs");
    

    Reading it from the inside out: result.find("cats") gives the start index, 4 is the number of characters in "cats", and "dogs" is the replacement. Writing the length as a bare number is easy to get wrong. When the text is stored in a variable, target.size() is safer than a number you counted by hand.

    When the text is missing

    If find finds nothing it returns string::npos, a huge value. Passing that as the position to replace makes the call throw std::out_of_range, and the program ends unless the exception is caught. Check first when the text may be absent:

    size_t pos = result.find("cats");
    if (pos != string::npos) {
        result.replace(pos, 4, "dogs");
    }
    

    If the length is larger than what remains after pos, C++ does not complain. It simply uses everything up to the end, so "abc" with replace(1, 100, "X") becomes "aX".

    Replacing every occurrence

    A single replace call changes only one range, and a single find returns only the first match. With "cats and cats", one call turns the first word into "dogs" and leaves the second. To change all of them, loop: find from a start position, replace, move the start past the new text, and stop when find returns npos. Moving the start past the replacement matters. If the new text contains the old text, starting at the same place can loop forever.

    The exercise, step by step

    The editor starts with string sentence = "I love cats";, and the task is to produce the same sentence with "cats" replaced by "dogs".

    1. Copy the sentence. Declare a string named result and initialize it from sentence. This keeps the original text intact and gives you something to change.
    2. Locate "cats". result.find("cats") returns 7.
    3. Replace by position and length. Call result.replace with that index, the length 4, and "dogs".
    string sentence = "I love cats";
    
    string result = sentence;
    result.replace(result.find("cats"), 4, "dogs");
    

    Afterwards result holds "I love dogs", and sentence is still "I love cats". Searching in result and not in sentence is deliberate: both strings hold the same text at that moment, but the index you find has to belong to the string you are about to change.

    Common mistakes

    • Giving the text to find where the position goes. The first argument is an index, not the old text.
    • Using the wrong length. Too short leaves part of the old word behind, and too long eats the characters after it.
    • Not checking for npos when the text may be absent.
    • Expecting the original to be unchanged without copying it first.

    Key takeaways

    • replace(pos, len, text) works on positions and changes the string itself.
    • Pair it with find to replace by content, and check for string::npos first if the text may be missing.
    • Copy the string first when you need to keep the original.
    Keep going with C++About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free