Replace part of a string with another string in C++


Here we will see how to replace a part of a string by another string in C++. In C++ the replacing is very easy. There is a function called string.replace(). This replace function replaces only the first occurrence of the match. To do it for all we have used loop. This replace function takes the index from where it will replace, it takes the length of the string, and the string which will be placed in the place of matched string.

Input: A string "Hello...Here all Hello will be replaced", and another string to replace "ABCDE"
Output: "ABCDE...Here all ABCDE will be replaced"

Algorithm

Step 1: Get the main string, and the string which will be replaced. And the match string
Step 2: While the match string is present in the main string:
Step 2.1: Replace it with the given string.
Step 3: Return the modified string

Example Code

 Live Demo

#include<iostream>
using namespace std;
main() {
   int index;
   string my_str = "Hello...Here all Hello will be replaced";
   string sub_str = "ABCDE";
   cout << "Initial String :" << my_str << endl;
   //replace all Hello with welcome
   while((index = my_str.find("Hello")) != string::npos) {    //for each location where Hello is found
      my_str.replace(index, sub_str.length(), sub_str); //remove and replace from that position
   }
   cout << "Final String :" << my_str;
}

Output

Initial String :Hello...Here all Hello will be replaced
Final String :ABCDE...Here all ABCDE will be replaced

Updated on: 30-Jul-2019

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements