Hi I'm looking for a function similar to std::string::compare() but outputs the position of the first element that doesn't match the string. Does a function like this exist in the standard library? Thanks in advance.
// Example program
#include <iostream>
#include <string>
#include <algorithm>
// outputs the position of the first element that doesn't match
int first_not_match(const std::string& a, const std::string& b)
{
int n = std::min(a.length(), b.length());
for (int i = 0; i < n; i++)
{
if (a[i] != b[i])
return i;
}
return n;
}
int main()
{
std::cout << first_not_match("", "") << '\n';
std::cout << first_not_match("1", "") << '\n';
std::cout << first_not_match("", "1") << '\n';
std::cout << first_not_match("1", "1") << '\n';
std::cout << first_not_match("cat", "cab") << '\n';
std::cout << first_not_match("call", "caller") << '\n';
}
Maybe there's a function in <algorithm> that could be used as a building block, but the STL is heavily iterator-based so you'd convert the iterator to an index.