简体   繁体   中英

C++ Merge Overlapping Strings

Let's say that I have string A: "info_mesh", and I want to add it string B: "mesh_foo".

However, I want string "info_mesh_foo", not string "info_meshmesh_foo".

I can't just say:

std::string A = "randomstuffoverlap", B = "overlapwithmorestuff"
std::string C = A + B;

Because I would end up with:

C = "randomstuffoverlapoverlapwithmorestuff",

when I want:

C = "randomstuffoverlapwithmorestuff"

without the "overlap" mentioned twice, as if the created string had a "mesh" of two strings.

However, I also would want this to work if:

std::string A = "juststuff", B = "unrelatedstuff", C;
//std::string C should be made equal to "juststuffunrelatedstuff".

(so there is No shared substring between them)

How would I go about doing this? Thanks in advance.

Try this;

std::string A = "randomstuffoverlap", B = "overlapwithmorestuff", C;
size_t pos = A.find_last_of(B[0]);
if (pos != std::string::npos)
{
    std::string::difference_type d = A.size() - pos;
    if (A.substr(pos) == B.substr(0, d))
        C = A + B.substr(d);
    else
        C = A + B;
}
else
    C = A + B;
std::cout << C << std::endl;

Well, starting with the maximum possible (full overlap), loop down until it fits, and then return the result from overlapping them:

std::string overlap(std::string_view a, std::string_view b) {
    for (auto n = std::min(a.size(), b.size());; --n) {
        if (b.endswith(a.substr(0, n))) // b.substr(b.size() - n) == a.substr(0, n)
            return std::string(b) + a.substr(n);
        else if (a.endswith(b.substr(0, n))) // a.substr(a.size() - n) == b.substr(0, n)
            return std::string(a) + b.substr(n);
}

If you cannot use C++20 std::string_view::endswith() , use the alternative in the comment.

This has taken me a while, but I have this function:

string overlapjoin(string a, string b) {
    for (long long x = (b.length()<= a.length())? b.length(): a.length(); x > 0; --x)
        if (a.substr(a.length() - x, a.length() - 1) == b.substr(0, x))
            return(a.substr(0, a.length() - x) + b);
    return(a + b);
}

Which can also be expressed as, if you want a limit to shared characters:

string overlapjoin(string a, string b, int maxlength) {
    for (long long x = maxlength; x > 0; --x)
        if (a.substr(a.length() - x, a.length() - 1) == b.substr(0, x))
            return(a.substr(0, a.length() - x) + b);
    return(a + b);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM