In this C++ tutorial, you will learn how to replace a substring in a string using std::string::replace(). You will also learn how to find and replace text, replace all occurrences of a substring, remove part of a string, and handle common replace() edge cases.

C++ String Replace

To replace part of a C++ string, use the replace() member function of std::string. You specify where the replacement starts, how many characters should be removed, and the new text that should be inserted.

The replacement text does not have to contain the same number of characters as the text being replaced. Therefore, replace() can make the string shorter, longer, or keep its length unchanged.

Syntax of std::string::replace()

Following is the syntax of std::string::replace() method.

</>
Copy
std::string &std::string::replace(std::size_t __pos, std::size_t __n1, const char *__s)

where:

  • __pos is the index of first character to replace.
  • __n1 is the number of characters to be replaced.
  • __s is the new string to insert.

String indexes are zero-based, so the first character is at position 0, the second is at position 1, and so on.

replace() method modifies the string in-place and also returns reference to this modified string.

Example – Replace Part of String with Another String

In this example, we shall take a string "Hello user! Good morning." and replace the part of this string that starts at position 10, and spans a length of 5, with new string "ooo".

C++ Program

</>
Copy
#include <iostream>
using namespace std;

int main() {
   string str = "Hello user! Good morning.";
   str.replace(10, 5, "ooo");

   cout << str  << endl;
}

Output

Hello useroood morning.

Here, replace(10, 5, "ooo") removes five characters beginning at index 10 and inserts the three characters in "ooo" at the same position.

Example – Replace String without Modifying Original String

In this example, we shall take a string "Hello user! Good morning." and replace the part of this string that starts at position 10, and spans a length of 5, with new string "ooo".

As replace() method modifies the string in-place, we have to make a copy of the original string by some means. We will use substr() method. substr() method() with starting position as 0 returns a copy of the original string. We shall then apply replace() method on this string copy.

C++ Program

</>
Copy
#include <iostream>
using namespace std;

int main() {
   string str = "Hello user! Good morning.";
   string str1 = str.substr(0).replace(10, 5, "ooo");

   cout << str  << endl;
   cout << str1 << endl;
}

Output

Hello user! Good morning.
Hello useroood morning.

A more direct way to preserve the original is to create a normal copy first and call replace() on the copy. This can make the intent easier to read when additional operations are required.

</>
Copy
#include <iostream>
#include <string>
using namespace std;

int main() {
    string original = "Hello user! Good morning.";
    string modified = original;

    modified.replace(10, 5, "ooo");

    cout << original << '\n';
    cout << modified << '\n';
}

Find and Replace a Substring in C++

In many programs, you know the text that has to be replaced but do not know its numeric position. In that case, use std::string::find() to locate the substring and pass the returned position to replace().

</>
Copy
#include <iostream>
#include <string>
using namespace std;

int main() {
    string text = "I like Java programming.";
    string oldText = "Java";
    string newText = "C++";

    size_t pos = text.find(oldText);

    if (pos != string::npos) {
        text.replace(pos, oldText.length(), newText);
    }

    cout << text << '\n';
}

Output

I like C++ programming.

find() returns the position of the first matching substring. When there is no match, it returns std::string::npos. Checking for npos prevents an invalid position from being passed to replace().

Replace All Occurrences of a Substring in C++

std::string::replace() operates at a specified position; it does not automatically search the entire string for every occurrence. To replace all occurrences, repeatedly call find() and replace().

</>
Copy
#include <iostream>
#include <string>
using namespace std;

int main() {
    string text = "red car, red bus, red bike";
    string oldText = "red";
    string newText = "blue";

    if (!oldText.empty()) {
        size_t pos = 0;

        while ((pos = text.find(oldText, pos)) != string::npos) {
            text.replace(pos, oldText.length(), newText);
            pos += newText.length();
        }
    }

    cout << text << '\n';
}

Output

blue car, blue bus, blue bike

After each replacement, the search position is advanced by the length of the replacement text. This prevents the loop from immediately searching inside text that was just inserted. Checking that oldText is not empty is also important because repeatedly searching for an empty substring can otherwise produce an unintended loop.

Remove a Substring with std::string::replace()

You can remove part of a C++ string by replacing it with an empty string. The following example removes "very " from a sentence.

</>
Copy
#include <iostream>
#include <string>
using namespace std;

int main() {
    string text = "C++ is very useful.";
    size_t pos = text.find("very ");

    if (pos != string::npos) {
        text.replace(pos, 5, "");
    }

    cout << text << '\n';
}

Output

C++ is useful.

For code whose only purpose is deletion, std::string::erase() is another direct option. Using replace() with an empty replacement is useful when the same replacement logic also handles non-empty replacement strings.

Replace One Character in a C++ String

If you already know the character position, you can replace one character by specifying a count of 1.

</>
Copy
#include <iostream>
#include <string>
using namespace std;

int main() {
    string text = "cat";
    text.replace(0, 1, "b");

    cout << text << '\n';
}

Output

bat

When replacing a single character with another single character, direct indexing such as text[0] = 'b'; is often simpler. The replace() function becomes especially useful when one character must be replaced with multiple characters or a larger substring.

How Position and Count Behave in std::string::replace()

  • If the replacement text is longer than the removed text, the string grows.
  • If the replacement text is shorter than the removed text, the string shrinks.
  • If the requested character count extends beyond the end of the string, replacement continues only through the available characters.
  • If the starting position is greater than the string size, replace() can throw std::out_of_range.
  • A position equal to the current string size can be used with a zero removal count to insert text at the end.

std::string::replace() versus std::regex_replace()

Use std::string::replace() when you are replacing text at a known position, or when you can locate literal text with find(). If the text to match is described by a pattern rather than an exact substring, C++ also provides std::regex_replace() through the regular-expression library. For ordinary literal substring replacement, find() with replace() is usually the more direct approach.

Common C++ String Replacement Mistakes

  • Using a character position as if indexing started at 1: C++ string positions start at 0.
  • Calling replace() with the result of find() without checking it: first verify that the result is not std::string::npos.
  • Expecting replace() to replace every match: one call replaces only the characters at the specified position.
  • Forgetting that replace() modifies the original string: make a copy first when the original value must remain unchanged.
  • Advancing incorrectly in a replace-all loop: continue searching after the inserted replacement text to avoid repeatedly processing newly inserted characters.
  • Using an empty search string in a replace-all loop: validate the search text before entering the loop.

C++ std::string::replace() Summary

In this C++ Tutorial, we learned the syntax of replace() function, and how to use it, with the help of example C++ programs.

Use std::string::replace(position, count, replacement) when the replacement position is known. When you know the old text instead of its position, locate it with find() first. To replace every occurrence, repeat the find-and-replace operation until find() returns std::string::npos.