Minimize length of a string by removing occurrences of another string from it as a substring


In this article, we delve into a challenging and interesting string manipulation problem in C++. The problem we're discussing today is "Minimize the length of a string by removing occurrences of another string from it as a substring". This problem is an excellent exercise in understanding strings, substrings, and algorithmic thinking.

Problem Statement

Given two strings, the task is to minimize the length of the first string by removing all occurrences of the second string from the first string as a substring.

C++ Solution Approach

Our approach will be to use the std::string::find and std::string::erase functions from the C++ Standard Library. The find function allows us to find the first occurrence of the second string in the first string, and erase allows us to remove this occurrence.

We'll repeatedly find and erase occurrences of the second string from the first string until there are no more occurrences left.

Example

Here's the C++ code that implements this solution −

#include <iostream>
#include <string>
using namespace std;

string minimizeString(string str, string sub) {
   size_t pos;
   while ((pos = str.find(sub)) != string::npos) {
      str.erase(pos, sub.length());
   }
   return str;
}

int main() {
   string str = "abcabcabc";
   string sub = "abc";
   string result = minimizeString(str, sub);
   cout << "The minimized string is: " << result << endl;
   return 0;
}

Output

The minimized string is: 

Explanation with a Test Case

Let's consider the strings "abcabcabc" and "abc".

When we pass these strings to the minimizeString function, it repeatedly finds and removes occurrences of the string "abc" from the string "abcabcabc" until there are no more occurrences left.

After all occurrences of "abc" have been removed, the first string is empty. So, the function returns an empty string.

Conclusion

This problem showcases how we can use the functions provided by the C++ Standard Library to manipulate strings and solve complex problems. It's a fantastic problem to practice your C++ coding skills and to understand how to work with strings and substrings.

Updated on: 18-May-2023

125 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements