Here's a comparison that handles any number of numeric values embedded in the strings:
#include <cstdlib>
#include <cctype>
#include <iostream>
#ifdef _MSC_VER
#define strtoll _strtoi64
#endif
int cmp(const char* lhs, const char* rhs)
{
while (*lhs || *rhs)
{
if (isdigit(*lhs) && isdigit(*rhs))
{
char* l_end;
char* r_end;
long long l = strtoll(lhs, &l_end, 10);
long long r = strtoll(rhs, &r_end, 10);
if (l < r) return -1;
if (l > r) return 1;
lhs = l_end;
rhs = r_end;
}
else
if (*lhs != *rhs)
return *lhs - *rhs;
else
++lhs, ++rhs;
}
return *lhs - *rhs;
}
It's deliberately "C style" so it can be applied directly and efficiently to character arrays. It returns a negative number if lhs < rhs
, 0 if they're equal, and a positive number if lhs > rhs
.
You can call this from a comparison functor or lambda specified to std::sort
.