比较c中的版本号

时间:2013-02-24 21:46:15

标签: c string-comparison version-numbering

我在其他语言中看到了很多关于这个问题的答案,但我试图找到一种方法来比较作为字符串给出的2个版本号。例如

str1 = "141.1.23"
str2 = "141.1.22"

我试图找到一种方法来比较字符串中的整数值,看看哪一个更大。 (在这种情况下,str1会更大)。我想过使用atoi和strtok的某些时候,但我知道我不能一次标记2个字符串。有什么建议吗?

6 个答案:

答案 0 :(得分:5)

  

我知道我不能一次对2个字符串进行标记。

幸运的是,你不需要:创建一个带字符串的函数,并使用strtok_r解析三个整数(使用可重入版本,它会更安全)。

strunct version_t {
    int major;
    int minor;
    int build;
};

version_t parse_ver(const char* version_str) {
    version_t res;
    // Use strtok_r to split the string, and atoi to convert tokens to ints
    return res;
}

现在,您可以拨打parse_ver两次,获取两个version_t值,并将它们并排比较。

P.S。如果采用约定来始终将带有前导零的数字填充到特定长度,即确保编写"141.1.03"而不是"141.1.3",则可以用字典编码替换整数比较。

答案 1 :(得分:3)

以下例程比较由真实数字组成的版本号字符串。优点是分隔符无关紧要;它可以使用,例如,141.01.03,141:1:3,甚至141A1P3。它还处理不匹配的尾部,以便141.1.3将在141.1.3.1之前出现。

#include <assert.h>
#include <stdlib.h>

int versionCmp( char *pc1, char *pc2)
{
    int result = 0;
    /* loop through each level of the version string */
    while (result == 0) {
        /* extract leading version numbers */
        char* tail1;
        char* tail2;
        unsigned long ver1 = strtoul( pc1, &tail1, 10 );
        unsigned long ver2 = strtoul( pc2, &tail2, 10 );
        /* if numbers differ, then set the result */
        if (ver1 < ver2)
            result = -1;
        else if (ver1 > ver2)
            result = +1;
        else {
            /* if numbers are the same, go to next level */
            pc1 = tail1;
            pc2 = tail2;
            /* if we reach the end of both, then they are identical */
            if (*pc1 == '\0' && *pc2 == '\0')
                break;
            /* if we reach the end of one only, it is the smaller */
            else if (*pc1 == '\0')
                result = -1;
            else if (*pc2 == '\0')
                result = +1;
            /*  not at end ... so far they match so keep going */
            else {
                pc1++;
                pc2++;
            }
        }
    }
    return result;
}

int main( void )
{
    assert(versionCmp("1.2.3" , "1.2.3" ) == 0);
    assert(versionCmp("1.2.3" , "1.2.4" )  < 0);
    assert(versionCmp("1.2.4" , "1.2.3" )  > 0);
    assert(versionCmp("10.2.4", "9.2.3" )  > 0);
    assert(versionCmp("9.2.4",  "10.2.3")  < 0);
    /* Trailing 0 ignored. */
    assert(versionCmp("01", "1") == 0);
    /* Any single space delimiter is OK. */
    assert(versionCmp("1a2", "1b2") == 0);
    return EXIT_SUCCESS;
}

strtoul替换为strcspnstrncmp,您可以使用它来比较非数字版本“数字” - 但分隔符必须是一个点。例如,141.3A.1在141.3B之前排序。

...
while (result == 0) {
    /* ignore leading zeroes */
    pc1 += strspn( pc1, "0" );
    pc2 += strspn( pc2, "0" );
    /* extract leading version strings */
    int len1 = strcspn( pc1, "." );
    int len2 = strcspn( pc2, "." );
    /* if one is shorter than the other, it is the smaller version */
    result = len1 - len2;
    /* if the same length then compare as strings */
    if (result == 0)
        result = strncmp( pc1, pc2, len1 );
    if (result == 0) {
        pc1 += len1;
        pc2 += len2;
        if (*pc1 == '\0' && *pc == '\0')
            ...

答案 2 :(得分:3)

strverscmp glibc扩展程序

示例:

#define _GNU_SOURCE
#include <assert.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    assert(strverscmp("1.2.3" , "1.2.3" ) == 0);
    assert(strverscmp("1.2.3" , "1.2.4" )  < 0);
    assert(strverscmp("1.2.3" , "1.2.2" )  > 0);
    assert(strverscmp("9.2.3" , "10.2.3")  < 0);
    assert(strverscmp("10.2.3", "9.2.3" )  > 0);

    /* Delimiers are also compared. */
    assert(strverscmp("1a2", "1b2" ) < 0);
    assert(strverscmp("1b2", "1a2" ) > 0);

    /* Leading 0s: number gets treated as 0.X, e.g. 01 means 0.1.
     * Maybe not perfect for version strings, but sane version strings
     * should not have leading 0s. 
     */
    assert(strverscmp("01", "9" ) < 0);
    assert(strverscmp("01", "09") < 0);
    assert(strverscmp("01", "09") < 0);
    assert(strverscmp("09",  "1") < 0);

    return EXIT_SUCCESS;
}

来源:https://sourceware.org/git/?p=glibc.git;a=blob;f=string/strverscmp.c;h=96d4227cd50090f3a7c45e7241d817d34e42f5ce;hb=cbc06bc486635347ee0da51d04a82eedf51602d5#l42

在Glibc 2.21,Ubuntu 15.10上测试。

来自gnulib的

filevercmp

又一个GNU实现。资料来源:http://git.savannah.gnu.org/cgit/gnulib.git/tree/libfilevercmp.c?id=71be4c87c8267369f40fbfab7523ab9847154c02#n125

它在Coreutils 8.23的sort -V中使用,其工作方式如下:https://stackoverflow.com/a/4024263/895245

答案 3 :(得分:1)

我真的很想知道为什么当C中存在sscanf时人们为什么会争取如此复杂的解决方案。这是一个非常简单的解决方案,将适用于所有用例的99%:

int compVersions ( const char * version1, const char * version2 ) {
    unsigned major1 = 0, minor1 = 0, bugfix1 = 0;
    unsigned major2 = 0, minor2 = 0, bugfix2 = 0;
    sscanf(version1, "%u.%u.%u", &major1, &minor1, &bugfix1);
    sscanf(version2, "%u.%u.%u", &major2, &minor2, &bugfix2);
    if (major1 < major2) return 1;
    if (major1 > major2) return -1;
    if (minor1 < minor2) return 1;
    if (minor1 > minor2) return -1;
    if (bugfix1 < bugfix2) return 1;
    if (bugfix1 > bugfix2) return -1;
    return 0;
}

在这里,尝试一下: https://ideone.com/IVz84k

答案 4 :(得分:0)

我们可以按照建议使用strtok。看看这段代码。为了简化它,我在c ++中使用vector,请使用其他容器或数据结构,例如初始化为两个字符串的最大长度的数组来保存标记化元素。

vector<char*> tokenize(char *s)
{
    vector<char*> svec;

    char *stp = strtok(s,".");
    while(stp != NULL)
    {
            svec.push_back(stp);
            stp = strtok(NULL,".");
    }
    cout << endl;
    return svec;

}

int version_compare(char *s1, char *s2)
{
    vector<char*> tokens_s1 = tokenize(s1);
    vector<char*> tokens_s2 = tokenize(s2);

    int st1, st2, flag, maxf,result;
    st1 = tokens_s1.size();
    st2 = tokens_s2.size();
    flag = st1 < st2 ? st1 : st2;


    for(int i=0; i < flag ;i++)
    {

            int one = *(tokens_s1[i]);
            int two = *(tokens_s2[i]);
            if(one > two)
                     return 1;
            else if(one < two)
                    return 2;
            else
                    result = 0;

    }
}

    if((st1 == st2) && (result == 0)) return 0;
    return (st1 > st2 ? 1 : 2);



}


int main()
{
    char s1[] = "1.2.3.4";
    char s2[] = "2.2.3.3.3";
    int st;
    st = version_compare(s1,s2);
    cout<<st<<endl;

}

答案 5 :(得分:0)

仅对第一个非匹配组件进行标记的极简主义C版本。使用strchr()和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;
            }
        }
    }
}