comparing version numbers in c

后端 未结 6 819
误落风尘
误落风尘 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 05:52

    I really wonder why people strive for such complicated solutions when there is sscanf in C. Here is a very simple solution to that problem that will work for 99% of all use cases:

    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;
    }
    

    Here, give it a try: https://ideone.com/bxCjsb

提交回复
热议问题