Merge two strings with common start and end substrings

advertisements

I have two strings the ending substring of first is the starting substring of the second,ex

string left : ONESTRING
string right : STRINGTWO

I have to merge them so that the resulting string is

result string : ONESTRINGTWO

The length of the common substring is not known in advance. If the starting and ending strings are not common, i need to return the concatenation of the strings.

This is what i am doing currently.

for(int i = 1;i< left.length();i++) {
        //substring of length "i" from last of left string
        string temp = left.substr(left.length() -1 -i,i);
        if(temp.length() < right.length()) {
            //check if the right string starts with the above substring
            if (strncmp(right.c_str(), temp.c_str(), strlen(temp.c_str())) == 0 ) {
                // common substring found, save this result
                found =  true;
                result = left.substr(0,left.length()-i-1) + right;
            }

        }
    }

if(found == true) {
    return result;
} else {
    return left + right;
}

I would be thankful for any pointers to a simpler implementation (in any language ).


By smart use of pointer arithmetic, you can skip the calls to substr (which do allocation) and strlen (which take O(n) time in the length of the string).

std::string concat(std::string const &left, std::string const &right)
{
    size_t n = left.length();
    for (size_t i=0; i<n; i++)
        if (std::strncmp(left.c_str() + i, right.c_str(), n - i) == 0)
            return left + (right.c_str() + n - i);

    return left + right;
}