Find And Replace in String in C++

Suppose we have a string S, we will perform some replacement operations that replace groups of letters with new ones. In each replacement operation there are 3 parameters − a starting index i, a source word x and a target word y. Now the rule is that if x starts at position i in the original string S, then we will replace that occurrence of x with y. otherwise, we do nothing.

So as an example, consider, if we have S = "abcd" and we have some replacement operation i = 2, x = "cd", y = "ffff", then because "cd" starts at position 2 in the original string S, we have to replace this with "ffff".

Let us see another example on S = "abcd", if we have both the replacement operation i = 0, x = "ab", y = "eee", as well as another replacement operation i = 2, x = "ec", y = "ffff", this second operation does nothing because in the original string S[2] = 'c', which doesn't match x[0] = 'e'.

So if we have a string S = “abcd”, indices = [0,2] and sources = [“a”, “cd”], and targets = [“eee”, “ffff”], then the output will be “eeebffff”. This is because "a" starts at position 0 in S, so it's replaced by "eee". Now "cd" starts at index 2 in S, so it's replaced by "ffff".

To solve this, we will follow these steps −

  • Define an array of pairs, called sorted, n := size of indexes array
  • for i in range 0 to n – 1
    • insert a pair (indexes[i], i) into sorted.
  • sort the sorted in reverse order
  • for j in range 0 to n – 1
    • i := first value of the pair sorted[j]
    • src := sources[second value of the pair sorted[j]]
    • target := targets[second value of the pair sorted[j]]
    • if substring of S from index i to size of sources – 1 is same as source, then
      • S := (substring of S from index 0 to i) concatenate target, concatenate (substring of S from i to size of sources – 1)
  • return S

Let us see the following implementation to get better understanding −


 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   string findReplaceString(string S, vector<int>& indexes, vector<string>& sources,       vector<string>& targets) {
      vector < pair <int, int> > sorted;
      int n = indexes.size();
      for(int i = 0; i < n; i++){
         sorted.push_back({indexes[i], i});
      sort(sorted.rbegin(), sorted.rend());
      for(int j = 0; j < n; j++){
         int i = sorted[j].first;
         string source = sources[sorted[j].second];
         string target = targets[sorted[j].second];
         if(S.substr(i, source.size()) == source){
            S = S.substr(0, i) + target + S.substr(i + source.size());
      return S;
   vector<int> v1 = {0, 2};
   vector<string> v2 = {"a", "cd"};
   vector<string> v3 = {"eee", "ffff"};
   Solution ob;
   cout << (ob.findReplaceString("abcd", v1, v2, v3));


[0, 2]
["a", "cd"]
["eee", "ffff"]