Remove last n occurrences of substring in a string in C++

This tutorial will see how to remove the last n occurrences of the substring in a string in C++. The string is said to be substring if each character from it is present in the parent string. A substring can be a set of characters or a single character.

Algorithm

  • Step 1: Declare the string from which you want to remove the substring. And declare the substring which you want to delete from the parent string.
  • Step 2: Declare integer n which is the last number of occurrences of a substring in the parent string. Declare another integer for position to use while iterating through the parent string with value -1.
  • Step 3: Using a loop iterate through the parent string n times. find the last occurrence of a substring using the rfind() function. Once the substring is found, we remove it using the erase() function.
    1.  rfind(sub, pos): This function returns the position of the last occurrence of the substring in the parent string, starting the search from the last position. It returns std::string::npos if the substring is not found. It takes two arguments one is a substring and the other is a position integer.
    2. erase(pos, sub.length()): This function is used to remove the characters from the string. It takes two arguments, first the position from where we want to remove the characters, and second the number of characters we want to remove.
  • Step 4: After finding the substring here we are removing the substring by passing the position of the substring and length. Finally, print the modified parent string.

 C++ Code: Remove last n occurrences of substring in a string

Here is the C++ code for removing the last n occurrences of the substring in a string.

#include <iostream>
#include <string>

int main() 
{
    std::string str = "This is a test sub string with multiple sub substring.";
    std::string sub = "sub";
    int n = 2;

    int pos = -1;
    for (int i = 0; i < n; i++) 
    {
        pos = str.rfind(sub, pos);
        if (pos == std::string::npos) 
        {
            std::cout << "Substring not found." << std::endl;
            break;
        }
        str.erase(pos, sub.length());
    }
    std::cout << str << std::endl;
    return 0;
}

Output:

This is a test sub string with multiple  string.

Also, refer to How to remove odd frequency characters from a string in C++

Leave a Reply

Your email address will not be published. Required fields are marked *