Different substrings in a string that start and end with given strings in C++ Program

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that finds the total number of substrings that starts and ends with the given strings.

We are given one string and two substrings. We need to find the different substrings count that starts and ends with the given two substrings. Let's see an example.

Input

str = "getmesomecoffee"
start = "m"
end = "e"

Output

6

There are a total of 6 different substrings in the given string. They are me, mesome, mesomemecoffe, mesomemecoffee, mecoffe, mecoffee.

Let's see the steps to solve the problem.

  • Initialize the strings.

  • Iterate over the str and find the start and end substrings indexes. Store them in separate arrays.

  • Initialize a set to store the different substrings.

  • Iterate over the str.

    • Check whether the current index matches the start string of the array we formed before.

    • If we found the start strings index, then search for the end string.

    • Add all the strings until we find an end to a variable.

    • When we find the end string, increment the substring count and add the substring to the set.

    • Reset the substring variable.

  • Print the substrings count.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int getSubstringsCount(string str, string start, string end) {
   int substrings_count = 0, str_length = str.size(), start_length = start.size(), end_length = end.size();
   int start_matches_index[str_length] = {0}, end_matches_index[str_length] = {0};
   for (int i = 0; i < str_length; i++) {
      if (str.substr(i, start_length) == start) {
         start_matches_index[i] = 1;
      }
      if (str.substr(i, end_length) == end) {
         end_matches_index[i] = 1;
      }
   }
   set<string> substrings;
   string current_substring = "";
   for (int i = 0; i < str_length; i++) {
      if (start_matches_index[i]) {
         for (int j = i; j < str_length; j++) {
            if (!end_matches_index[j]) {
               current_substring += str[j];
            }
            if (end_matches_index[j]) {
               current_substring += str.substr(j, end_length);
               if (substrings.find(current_substring) == substrings.end()) {
                  substrings_count++;
               }
               substrings.insert(current_substring);
            }
         }
         current_substring = "";
      }
   }
   return substrings_count;
}
int main() {
   string str = "getmesomecoffee";
   string start = "m";
   string end = "e";
   cout << getSubstringsCount(str, start, end) << endl;
   return 0;
}

Output

If you execute the above program, then you will get the following result.

6

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 27-Jan-2021 12:38:56
Advertisements