Home > Software engineering >  C equivalent of Java StringUtils.indexOfDifference
C equivalent of Java StringUtils.indexOfDifference

Time:02-11

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?

CodePudding user response:

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

CodePudding user response:

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");

}
  • Related