'Cannot use the substr function after using erase

I am trying to solve a problem on usaco which is give a string S and another string smaller than it T and ask to remove all the occurences of T in S.

so my approach is to iterate over S and check whether the last substring of it is equal to T, if that is the case i will erase it, but the problem is after i erase the first occurence, the substr function is not working anymore.

Here is te code

#include <bits/stdc++.h>

using namespace std;

int main()
{
ifstream fin ("censor.in");
ofstream fout ("censor.out");

string s,t; fin >> s >> t;

int n = s.size(), m = t.size();

string censored;

for(int i = 0; i < n; i++)
{
    censored += s[i];

    if(censored.size() > m && censored.substr(i - (m-1) , m) == t)
    {
        censored.erase(i- (m-1), i);
    }
        
}

fout<< censored << '\n';

}

and the content of the file censor.in is :

whatthemoommomooooofun moo

the solution should be:

whatthefun



Solution 1:[1]

After you erase characters from the string, neither the size nor the indexes will no longer match what you originally had. You need to recalculate the string length, as well as the index i.

credit: Some programmer dude

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Quicksvolex