Search code examples
c++stringstring-comparison

Comparing two strings that return the equivalent substring in c++


I have a function subString that takes in two strings. I loop through my first string to generate substrings of at least size >= 4. I want to find a substring that exists in my second string. For example:

string1: "ABCDE" string2: "XYBCDEFGH"

substrings of string1 include: "ABCD", "ABCDE", "BCDE"

So, I want to compare the substrings generated to string2 and return "BCDE"

I'm confused on how to compare the two strings. I looked through the STL string library (https://www.cplusplus.com/reference/string/string/), but I got stuck trying to find the right method for this problem.

#include <iostream>
#include <string> 

using namespace std;

void subString(string s1, string s2){
    int n = 4;
    int strLength = s1.length();
    string firstString;
    
    for (int i = 0; i < strLength; i++){
        for(int j = 1; j <= strLength - i; j++){
            if (s1.substr(i,j).length() >= n){
                firstString = s1.substr(i,j);
                cout << firstString << endl;
            }
        }
    }
}

int main()
{
    string s1;
    string s2;
    
    cin >> s1;
    cin >> s2;
    subString(s1, s2);
}

Solution

  • You could

    1. Return a vector of substrings.
    2. Then loop through the vector and search in s2 string using find method.

    See below code sample.

    #include <iostream>
    #include <string> 
    #include <vector>
    
    using namespace std;
    
    vector<string> subString(string s1, string s2){
        int n = 4;
        int strLength = s1.length();
        string firstString;
        vector<string> substrings;
        
        for (int i = 0; i < strLength; i++){
            for(int j = 1; j <= strLength - i; j++){
                if (s1.substr(i,j).length() >= n){
                    firstString = s1.substr(i,j);
                    substrings.push_back(firstString);
                }
            }
        }
        return substrings;
    }
    
    int main()
    {
        string s1 = "ABCDE";
        string s2 = "XYBCDEFGH";
    
        for (auto value : subString(s1, s2))
        {
            if (s2.find(value) != string::npos)
                cout << "found " << value << endl;
        }
    }
    

    Output of this code

    found BCDE