In this C++ tutorial, you will learn how to replace a substring in a string with new replacement using std::string::replace() function, with example programs.

C++ String Replace

To replace part of a string that starts at given position and spans a specific length in the main string with a new string, you can use std::string::replace() function.

Syntax of std::string::replace()

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

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.

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

#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.

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

#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.

Conclusion

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