Remove last occurrence of a word from a given sentence string | Java 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
import java . util . * ; class GFG { static String removeLastOccurrence ( String S , String W , int N , int M ) { char [ ] ch = S . toCharArray ( ) ; if ( M > N ) return S ; for ( int i = N - M ; i >= 0 ; i -- ) { int flag = 0 ; for ( int j = 0 ; j < M ; j ++ ) { if ( ch [ j + i ] != W . charAt ( j ) ) { flag = 1 ; break ; } } if ( flag == 0 ) { for ( int j = i ; j < N - M ; j ++ ) ch [ j ] = ch [ j + M ] ; break ; } } char [ ] chh = new char [ N - M ] ; for ( int i = 0 ; i < N - M ; i ++ ) { chh [ i ] = ch [ i ] ; } return String . valueOf ( chh ) ; } public static void main ( String [ ] args ) { String S = " This ▁ is ▁ GeeksForGeeks " ; String W = " Geeks " ; int N = S . length ( ) ; int M = W . length ( ) ; System . out . print ( removeLastOccurrence ( S , W , N , M ) ) ; } }