Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,987 questions

51,931 answers

573 users

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
...