Remove last occurrence of a word from a given sentence string
Last Updated :
07 Oct, 2023
Given two strings S and W of sizes N and M respectively, the task is to remove the last occurrence of W from S. If there is no occurrence of W in S, print S as it is.
Examples:
Input: S = “This is GeeksForGeeks”, W="Geeks"
Output: This is GeeksFor
Explanation:
The last occurrence of “Geeks” in the string is substring over the range [16, 20].
Input: S="Hello World", W="Hell"
Output: o World
Explanation:
The last occurrence of “Hell” in the string is substring over the range [0, 3].
Approach: The problem can be solved by iterating over every index i of string S and checking if there is a substring starting from the index i, which is equal to string W. Follow the steps below to solve the problem:
- If N is smaller than M, print S, as there can be no occurrence of W in S.
- Initialize a variable i as N-M to iterate over the string S.
- Iterate until i is greater than 0 and perform the following steps:
- Check whether the substring over the range [i, i+M-1] is equal to string W or not. If it is equal, then remove the substring over the range [i, i+M-1] from string S and then break.
- Otherwise, continue.
- Finally, after completing the above steps, print the string S as the answer.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to remove last occurrence
// of W from S
string removeLastOccurrence(string S, string W, int N,
int M)
{
// If M is greater than N
if (M > N)
return S;
// Iterate while i is greater than
// or equal to 0
for (int i = N - M; i >= 0; i--) {
// Stores if occurrence of W has
// been found or not
int flag = 0;
// Iterate over the range [0, M]
for (int j = 0; j < M; j++) {
// If S[j+1] is not equal to
// W[j]
if (S[j + i] != W[j]) {
// Mark flag true and break
flag = 1;
break;
}
}
// If occurrence has been found
if (flag == 0) {
// Delete the substring over the
// range [i, i+M]
for (int j = i; j < N - M; j++)
S[j] = S[j + M];
// Resize the string S
S.resize(N - M);
break;
}
}
// Return S
return S;
}
// Driver Code
int main()
{
// Input
string S = "This is GeeksForGeeks";
string W = "Geeks";
int N = S.length();
int M = W.length();
// Function call
cout << removeLastOccurrence(S, W, N, M) << endl;
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to remove last occurrence
// of W from S
static String removeLastOccurrence(String S, String W,
int N, int M)
{
// If M is greater than N
char[] ch = S.toCharArray();
if (M > N)
return S;
// Iterate while i is greater than
// or equal to 0
for(int i = N - M; i >= 0; i--)
{
// Stores if occurrence of W has
// been found or not
int flag = 0;
// Iterate over the range [0, M]
for(int j = 0; j < M; j++)
{
// If S[j+1] is not equal to
// W[j]
if (ch[j + i] != W.charAt(j))
{
// Mark flag true and break
flag = 1;
break;
}
}
// If occurrence has been found
if (flag == 0)
{
// Delete the substring over the
// range [i, i+M]
for(int j = i; j < N - M; j++)
ch[j] = ch[j + M];
break;
}
}
char[] chh = new char[N - M];
// Resize the string S
for(int i = 0; i < N - M; i++)
{
chh[i] = ch[i];
}
// Return S
return String.valueOf(chh);
}
// Driver Code
public static void main(String[] args)
{
// Input
String S = "This is GeeksForGeeks";
String W = "Geeks";
int N = S.length();
int M = W.length();
// Function call
System.out.print(removeLastOccurrence(S, W, N, M));
}
}
// This code is contributed by sanjoy_62
Python3
# Python3 program for the above approach
# Function to remove last occurrence
# of W from S
def removeLastOccurrence(S, W, N, M):
S = [i for i in S]
W = [i for i in W]
# If M is greater than N
if (M > N):
return S
# Iterate while i is greater than
# or equal to 0
for i in range(N - M, -1, -1):
# of W has
# been found or not
flag = 0
# Iterate over the range [0, M]
for j in range(M):
# If S[j+1] is not equal to
# W[j]
if (S[j + i] != W[j]):
# Mark flag true and break
flag = 1
break
# If occurrence has been found
if (flag == 0):
# Delete the subover the
# range [i, i+M]
for j in range(i,N-M):
S[j] = S[j + M]
# Resize the S
S = S[:N - M]
break
# Return S
return "".join(S)
# Driver Code
if __name__ == '__main__':
# Input
S = "This is GeeksForGeeks"
W = "Geeks"
N = len(S)
M = len(W)
# Function call
print (removeLastOccurrence(S, W, N, M))
# This code is contributed by mohit kumar 29.
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
// Function to remove last occurrence
// of W from S
static string removeLastOccurrence(string S, string W, int N,
int M)
{
// If M is greater than N
char[] ch = S.ToCharArray();
if (M > N)
return S;
// Iterate while i is greater than
// or equal to 0
for (int i = N - M; i >= 0; i--)
{
// Stores if occurrence of W has
// been found or not
int flag = 0;
// Iterate over the range [0, M]
for (int j = 0; j < M; j++) {
// If S[j+1] is not equal to
// W[j]
if (ch[j + i] != W[j]) {
// Mark flag true and break
flag = 1;
break;
}
}
// If occurrence has been found
if (flag == 0) {
// Delete the substring over the
// range [i, i+M]
for (int j = i; j < N - M; j++)
ch[j] = ch[j + M];
// Resize the string S
Array.Resize(ref ch,N - M);
break;
}
}
S = string.Concat(ch);
// Return S
return S;
}
// Driver Code
public static void Main()
{
// Input
string S = "This is GeeksForGeeks";
string W = "Geeks";
int N = S.Length;
int M = W.Length;
// Function call
Console.Write(removeLastOccurrence(S, W, N, M));
}
}
// This code is contributed by bgangwar59.
JavaScript
<script>
// JavaScript program for the above approach
// Function to remove last occurrence
// of W from S
function removeLastOccurrence(S, W, N, M)
{
// If M is greater than N
if (M > N)
return S;
// Iterate while i is greater than
// or equal to 0
for (let i = N - M; i >= 0; i--)
{
// Stores if occurrence of W has
// been found or not
let flag = 0;
// Iterate over the range [0, M]
for (let j = 0; j < M; j++) {
// If S[j+1] is not equal to
// W[j]
if (S[j + i] != W[j]) {
// Mark flag true and break
flag = 1;
break;
}
}
// If occurrence has been found
if (flag == 0) {
// Delete the substring over the
// range [i, i+M]
for (let j = i; j < N - M; j++)
S[j] = S[j + M];
// Resize the string S
S = S.substring(0,N - M);
break;
}
}
// Return S
return S;
}
// Driver Code
// Input
let S = "This is GeeksForGeeks";
let W = "Geeks";
let N = S.length;
let M = W.length;
// Function call
document.write(removeLastOccurrence(S, W, N, M),"</br>");
// This code is contributed by shinjanpatra
</script>
Time Complexity: O(M*N)
Auxiliary Space: O(1)
Approach:
To find the position of the last occurrence of W in S, we can use the rfind() function. This function returns the position of the last occurrence of the specified string in the calling string object. If the specified string is not found, the function returns string::npos, which is a constant value representing an invalid position or index.
Once we have the position of the last occurrence of W in S, we can use the erase() function to remove the substring containing W from S. The erase() function takes two arguments - the starting position from where the substring needs to be erased and the length of the substring to be erased.
If the string W is not present in S, the rfind() function will return string::npos, indicating that W is not present in S. In this case, we can simply return S as it is.
- Use the rfind() function to find the position of the last occurrence of string W in string S.
- If the string W is not present in S, return S as it is.
- If W is found in S, remove the substring containing W from S using the erase() function.
- Return the modified string S.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
// Function to remove last occurrence of W from S
string removeLastOccurrence(string S, string W, int N, int M)
{
// Find the position of the last occurrence of W in S
int pos = S.rfind(W);
// If W is not found in S, return S as it is
if (pos == string::npos)
return S;
// Remove the substring containing W from S
S.erase(pos, M);
return S;
}
// Driver Code
int main()
{
// Input
string S = "This is GeeksForGeeks";
string W = "Geeks";
int N = S.length();
int M = W.length();
// Function call
cout << removeLastOccurrence(S, W, N, M) << endl;
return 0;
}
Java
import java.util.*;
public class Main {
// Function to remove last occurrence of W from S
public static String
removeLastOccurrence(String S, String W, int N, int M)
{
// Find the position of the last occurrence of W in
// S
int pos = S.lastIndexOf(W);
// If W is not found in S, return S as it is
if (pos == -1)
return S;
// Remove the substring containing W from S
StringBuilder sb = new StringBuilder(S);
sb.delete(pos, pos + M);
return sb.toString();
}
// Driver Code
public static void main(String[] args)
{
// Input
String S = "This is GeeksForGeeks";
String W = "Geeks";
int N = S.length();
int M = W.length();
// Function call
System.out.println(
removeLastOccurrence(S, W, N, M));
}
}
Python3
def remove_last_occurrence(S, W):
# Find the position of the last occurrence of W in S
pos = S.rfind(W)
# If W is not found in S, return S as it is
if pos == -1:
return S
# Remove the substring containing W from S
S = S[:pos] + S[pos + len(W):]
return S
# Driver Code
if __name__ == "__main__":
# Input
S = "This is GeeksForGeeks"
W = "Geeks"
# Function call
print(remove_last_occurrence(S, W))
C#
using System;
class Program
{
// Function to remove last occurrence of W from S
static string RemoveLastOccurrence(string S, string W)
{
// Find the position of the last occurrence of W in S
int pos = S.LastIndexOf(W);
// If W is not found in S, return S as it is
if (pos == -1)
return S;
// Remove the substring containing W from S
S = S.Remove(pos, W.Length);
return S;
}
static void Main()
{
// Input
string S = "This is GeeksForGeeks";
string W = "Geeks";
// Function call
Console.WriteLine(RemoveLastOccurrence(S, W));
}
}
JavaScript
// Function to remove last occurrence of W from S
function removeLastOccurrence(S, W) {
// Find the position of the last occurrence of W in S
const pos = S.lastIndexOf(W);
// If W is not found in S, return S as it is
if (pos === -1)
return S;
// Remove the substring containing W from S
const sb = S.slice(0, pos) + S.slice(pos + W.length);
return sb;
}
// Driver Code
function main() {
// Input
const S = "This is GeeksForGeeks";
const W = "Geeks";
// Function call
console.log(removeLastOccurrence(S, W));
}
// Call the main function
main();
Time Complexity: O(N), where N is the length of string S.
Space Complexity: O(1), as we are not using any extra space.
Similar Reads
Remove all occurrences of a word from a given string using Z-algorithm
Given two strings str of length N and word of length M, the task is to remove all the occurrences of the string word from the string str. Examples: Input: str = "asmGeeksasmasmForasmGeeks", word = "asm" Output: GeeksForGeeks Explanation: Removing "asm" from the string, str modifies str to GeeksForGe
15+ min read
Python | Remove all duplicates words from a given sentence
Goal is to process a sentence such that all duplicate words are removed, leaving only the first occurrence of each word. Final output should maintain the order of the words as they appeared in the original sentence. Let's understand how to achieve the same using different methods:Using set with join
4 min read
Remove all the palindromic words from the given sentence
Given a sentence str. The problem is to remove all the palindromic words from the given sentence.Examples: Input : str = "Text contains malayalam and level words" Output : Text contains and words Input : str = "abc bcd" Output : abc bcd Approach: One by one extract all the words. Check if the curren
12 min read
Remove all occurrences of a character from a string using STL
Given a string S and a character C, the task is to remove all the occurrences of the character C from the given string. Examples: Input:vS = "GFG IS FUN", C = 'F' Output:GG IS UN Explanation: Removing all occurrences of the character 'F' modifies S to "GG IS UN". Therefore, the required output is GG
2 min read
Remove duplicates from string keeping the order according to last occurrences
Given a string, remove duplicate characters from the string, retaining the last occurrence of the duplicate characters. Assume the characters are case-sensitive. Examples: Input : geeksforgeeks Output : forgeks Explanation : Please note that we keep only last occurrences of repeating characters in s
8 min read
Count occurrences of a word in string
Given a two strings s and word. The task is to count the number of occurrences of the string word in the string s.Note: The string word should appear in s as a separate word, not as a substring within other words.Examples: Input: s = "GeeksforGeeks A computer science portal for geeks", word = "porta
11 min read
Remove all occurrences of string t in string s using KMP Algorithm
Given two strings s and t, the task is to remove all occurrences of t in s and return the modified string s, and you have to use the KMP algorithm to solve this. Examples: Input: s = "abcdefgabcabcabdefghabc", t = "abc"Output: "defgdefgh" Input: s = "aaabbbccc", t = "bbb"Output: "aaaccc" Approach: T
8 min read
Count occurrences of a word in string | Set 2 (Using Regular Expressions)
Given a string str and a word w, the task is to print the number of the occurrence of the given word in the string str using Regular Expression. Examples: Input: str = "peter parker picked a peck of pickled peppersâ, w = "peck"Output: 1Explanation: There is only one occurrence of the word "peck" in
4 min read
Remove duplicate words from Sentence using Regular Expression
Given a string str which represents a sentence, the task is to remove the duplicate words from sentences using regular Expression in Programming Languages like C++, Java, C#, Python, etc. Examples of Remove Duplicate Words from SentencesInput: str = "Good bye bye world world" Output: Good bye world
5 min read
Check if substring S1 appear after any occurrence of substring S2 in given sentence
Given strings S1, S2 and S, the task is to check if every substring of S which is same as S1 has another substring of S same as S2 before it. It is given that S1 is always present as a substring in the string S. Examples: Input: S1 = "code", S2 = "geek", S = "sxygeeksgcodetecode"Output: TrueExplanat
4 min read