comparing version numbers in c

后端 未结 6 817
误落风尘
误落风尘 2020-12-18 05:15

I am seeing a lot of answers for this problem in other languages but I am trying to find out a way to compare 2 version numbers given as strings. For example



        
6条回答
  •  感情败类
    2020-12-18 06:07

    A minimalist C version that only tokenizes the first non-matching component. Uses strchr() and strtoul().

    int version_compare(char *s1, char *s2)
    {
        char *delim = ".:-";
        while(1) {
            if (*s1 == *s2)  {
                if (!*s1)
                    return 0;
                s1++; s2++;
            } else if (strchr(delim, *s1) || !*s1) {
                return -1;
            } else if (strchr(delim, *s2) || !*s2) {
                return 1;
            } else {
                int diff;
                char *end1, *end2;
                diff = strtoul(c1, &end1, 10) - strtoul(c2, &end2, 10);
                if (!diff) {
                    c1 += (end1 - c1);
                    c2 += (end2 - c2);
                } else {
                    return diff;
                }
            }
        }
    }
    

提交回复
热议问题