Eugene
Eugene

Reputation: 11535

C++ equivalent of Java StringUtils.indexOfDifference

For C++20, is there a library equivalent of Java's StringUtils.indexOfDifference()?

What is the efficient way of comparing two large strings and determining where they differ?

Upvotes: 1

Views: 154

Answers (2)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122575

You can use std::mismatch if you take care about the different cases that lead to an end iterator in the result:

#include <algorithm>
#include <string>
#include <iterator>
#include <iostream>

void mism(const std::string& a, const std::string& b){
    auto its = std::mismatch(a.begin(), std::next(a.begin(),std::min(a.size(),b.size())),b.begin());
    if (its.first == a.end() && its.second == b.end()) {
        std::cout << "the strings are equal\n";
    } else if (its.first != a.end() && its.second != b.end()){
        std::cout << "the strings differ at " << *(its.first) << " and " << *(its.second) << "\n";
    } else if (its.first == a.end()) {
        std::cout << "the second string starts with the first\n";
    } else if (its.second == b.end()) {
        std::cout << "the first string start with the second\n";
    }
}
int main() {
    mism("foo1abc","foo2abc");
    mism("foo","foo");
    mism("foo123","foo");
    mism("foo","foo123");

}

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 117886

You can use std::mismatch from <algorithm>

Returns the first mismatching pair of elements from two ranges

For example

#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>

std::size_t IndexOfDifference(std::string const& lhs, std::string const& rhs) {
    auto diff = std::mismatch(lhs.begin(), lhs.end(), rhs.begin());
    return std::distance(lhs.begin(), diff.first);
}

int main() {
    std::cout << IndexOfDifference("foobar", "foocar");
}

Will output

3

Upvotes: 3

Related Questions