How to compare two version number strings in golang

前端 未结 10 738
别跟我提以往
别跟我提以往 2020-12-30 02:06

I have two strings (they are actually version numbers and they could be any version numbers)

a := \"1.05.00.0156\"  
b := \"1.0.221.9289\"

10条回答
  •  天涯浪人
    2020-12-30 02:25

    Here's a general solution.

    package main
    
    import "fmt"
    
    func VersionOrdinal(version string) string {
        // ISO/IEC 14651:2011
        const maxByte = 1<<8 - 1
        vo := make([]byte, 0, len(version)+8)
        j := -1
        for i := 0; i < len(version); i++ {
            b := version[i]
            if '0' > b || b > '9' {
                vo = append(vo, b)
                j = -1
                continue
            }
            if j == -1 {
                vo = append(vo, 0x00)
                j = len(vo) - 1
            }
            if vo[j] == 1 && vo[j+1] == '0' {
                vo[j+1] = b
                continue
            }
            if vo[j]+1 > maxByte {
                panic("VersionOrdinal: invalid version")
            }
            vo = append(vo, b)
            vo[j]++
        }
        return string(vo)
    }
    
    func main() {
        versions := []struct{ a, b string }{
            {"1.05.00.0156", "1.0.221.9289"},
            // Go versions
            {"1", "1.0.1"},
            {"1.0.1", "1.0.2"},
            {"1.0.2", "1.0.3"},
            {"1.0.3", "1.1"},
            {"1.1", "1.1.1"},
            {"1.1.1", "1.1.2"},
            {"1.1.2", "1.2"},
        }
        for _, version := range versions {
            a, b := VersionOrdinal(version.a), VersionOrdinal(version.b)
            switch {
            case a > b:
                fmt.Println(version.a, ">", version.b)
            case a < b:
                fmt.Println(version.a, "<", version.b)
            case a == b:
                fmt.Println(version.a, "=", version.b)
            }
        }
    }
    

    Output:

    1.05.00.0156 > 1.0.221.9289
    1 < 1.0.1
    1.0.1 < 1.0.2
    1.0.2 < 1.0.3
    1.0.3 < 1.1
    1.1 < 1.1.1
    1.1.1 < 1.1.2
    1.1.2 < 1.2
    

提交回复
热议问题