Remove last occurrence of a word from a given sentence string | C ++ program for the above approach ; Function to remove last occurrence of W from S ; If M is greater than N ; Iterate while i is greater than or equal to 0 ; Stores if occurrence of W has been found or not ; Iterate over the range [ 0 , M ] ; If S [ j + 1 ] is not equal to W [ j ] ; Mark flag true and break ; If occurrence has been found ; Delete the substring over the range [ i , i + M ] ; Resize the string S ; Return S ; Driver Code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; string removeLastOccurrence ( string S , string W , int N , int M ) { if ( M > N ) return S ; for ( int i = N - M ; i >= 0 ; i -- ) { int flag = 0 ; for ( int j = 0 ; j < M ; j ++ ) { if ( S [ j + i ] != W [ j ] ) { flag = 1 ; break ; } } if ( flag == 0 ) { for ( int j = i ; j < N - M ; j ++ ) S [ j ] = S [ j + M ] ; S . resize ( N - M ) ; break ; } } return S ; } int main ( ) { string S = " This ▁ is ▁ GeeksForGeeks " ; string W = " Geeks " ; int N = S . length ( ) ; int M = W . length ( ) ; cout << removeLastOccurrence ( S , W , N , M ) << endl ; return 0 ; }