Skip to content

Instantly share code, notes, and snippets.

@jedy
Last active August 29, 2015 14:00
Show Gist options
  • Save jedy/11129766 to your computer and use it in GitHub Desktop.
Save jedy/11129766 to your computer and use it in GitHub Desktop.
compare version
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int compareVersion(const char *v1, const char *v2)
{
char *f1, *f2, *s1, *s2;
int n1, n2, r;
f1 = s1 = strdup(v1);
f2 = s2 = strdup(v2);
do {
n1 = s1 ? atoi(strsep(&s1, ".")) : 0;
n2 = s2 ? atoi(strsep(&s2, ".")) : 0;
r = n1 - n2;
} while (!r && (s1 || s2));
free(f1);
free(f2);
return r;
}
int main()
{
printf("%d\n", compareVersion("1.2.0", "1.2.-1"));
printf("%d\n", compareVersion("1.2.1", "1.2.0"));
printf("%d\n", compareVersion("12.2", "2.2.0"));
printf("%d\n", compareVersion("1.2.1", "1.2"));
printf("%d\n", compareVersion("1.2.3", "1.2.1"));
printf("%d\n", compareVersion("1.2.3", "1"));
printf("%d\n", compareVersion("1", "1.0.3.1"));
printf("%d\n", compareVersion("1.2.3", "1.0.10"));
printf("%d\n", compareVersion("1.0.3", "1.1.10"));
printf("%d\n", compareVersion("1.1.03", "1.1.3"));
printf("%d\n", compareVersion("1.1.03", ""));
printf("%d\n", compareVersion("", "1.20"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment