How to merge two strings based on shared suffix and prefix in C++

1 Answer

0 votes
#include <string>
#include <iostream>
#include <algorithm>

std::string merge_on_overlap(const std::string& a, const std::string& b) {
    const std::size_t max_possible_overlap_len = std::min(a.size(), b.size());

    // Try longest possible overlap first
    for (std::size_t len = max_possible_overlap_len; len > 0; len--) {
        if (a.compare(a.size() - len, len, b, 0, len) == 0) {
            return a + b.substr(len);
        }
    }

    return a + b;
}

int main() {
    std::string a = "fantasy time travel technology";
    std::string b = "technology extraterrestrial life";

    std::cout << merge_on_overlap(a, b) << "\n";
}



/*
run:

fantasy time travel technology extraterrestrial life

*/

 



answered Jan 23 by avibootz
edited Jan 23 by avibootz
...