Replace Part of a String with Another String in C++



In this article, we will learn the different approaches to replace a part of a string with another string using a C/C++ program. The problem statement of this program is explained below:

The input of this problem will be three strings. The task is to replace all the occurrence of the second string with the third string inside the first string. For example:

// Input strings
"C++ Course is free on Tutorialspoint"
"C++"
"Python"

// Output String
"Python Course is free on Tutorialspoint"

Replace a Substring With Another String

Here is the list of all the approaches to replace a part of string (substring) with another string using c++ program, which we will be discussing in this article with stepwise explanation and complete example codes.

Using Regular Expression to Replace String

The regular expression is used to match and edit a string pattern in a larger string. In this method, we will use regex_replace() function to match all occurrence of given string inside the first string and replace it with third string. Let's see how to do it below.

Example

In the code below, the regular expression regex("\d+") will match with all the numbers in the string, and then the replace function replace those with XXX string.

#include <iostream>
#include <regex>
using namespace std;

int main() {
    string str = "Replace 123 and 456 with XXX";
    str = regex_replace(str, regex("\d+"), "XXX");
    cout << str; 
}

The output of the above code will be:

Replace XXX and XXX with XXX

Using find() Function to Replace String

The find() function is a member function of the string class in C++. It returns the position of the first occurrence of a substring in a string. In this method, we will use find() function to return the occurrence of the second string in the first string. Then the occurrence can be replaced with third string by using replace() function.

Example

In code below, we used the find() function to repeatedly find substring and the replace() function replaces the occurrence.

#include <iostream>
using namespace std;

int main() {
    string str = "I love C++";
    size_t pos = str.find("C++");
    if (pos != string::npos)
        str.replace(pos, 3, "Python");
    cout << str;  
}

The output of the above code will be:

I love Python
Updated on: 2025-04-24T10:12:24+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements