I want to write a cmp-like function which compares two version numbers and returns -1, 0, or 1 based on their compared va
This is my solution (written in C, sorry). I hope you'll find it useful
int compare_versions(const char *s1, const char *s2) {
while(*s1 && *s2) {
if(isdigit(*s1) && isdigit(*s2)) {
/* compare as two decimal integers */
int s1_i = strtol(s1, &s1, 10);
int s2_i = strtol(s2, &s2, 10);
if(s1_i != s2_i) return s1_i - s2_i;
} else {
/* compare as two strings */
while(*s1 && !isdigit(*s1) && *s2 == *s1) {
s1++;
s2++;
}
int s1_i = isdigit(*s1) ? 0 : *s1;
int s2_i = isdigit(*s2) ? 0 : *s2;
if(s1_i != s2_i) return s1_i - s2_i;
}
}
return 0;
}