How to compare two version number strings in golang

前端 未结 10 664
别跟我提以往
别跟我提以往 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:37

    This depends on what you mean by bigger.

    A naive approach would be:

    package main
    
    import "fmt"
    import "strings"
    
    func main() {
        a := strings.Split("1.05.00.0156", ".")
        b := strings.Split("1.0.221.9289", ".")
        for i, s := range a {
            var ai, bi int
            fmt.Sscanf(s, "%d", &ai)
            fmt.Sscanf(b[i], "%d", &bi)
            if ai > bi {
                fmt.Printf("%v is bigger than %v\n", a, b)
                break
            }
            if bi > ai {
                fmt.Printf("%v is bigger than %v\n", b, a)
                break
            }
        }
    }
    

    http://play.golang.org/p/j0MtFcn44Z

    0 讨论(0)
  • 2020-12-30 02:38

    There is a nice solution from Hashicorp - https://github.com/hashicorp/go-version

    import github.com/hashicorp/go-version
    v1, err := version.NewVersion("1.2")
    v2, err := version.NewVersion("1.5+metadata")
    // Comparison example. There is also GreaterThan, Equal, and just
    // a simple Compare that returns an int allowing easy >=, <=, etc.
    if v1.LessThan(v2) {
        fmt.Printf("%s is less than %s", v1, v2)
    }
    
    0 讨论(0)
  • 2020-12-30 02:43

    Some time ago I created a version comparison library: https://github.com/mcuadros/go-version

    version.CompareSimple("1.05.00.0156", "1.0.221.9289")
    //Returns: 1
    

    Enjoy it!

    0 讨论(0)
  • 2020-12-30 02:43

    Based on Jeremy Wall's answer:

      func compareVer(a, b string) (ret int) {
                as := strings.Split(a, ".")
                bs := strings.Split(b, ".")
                loopMax := len(bs)
                if len(as) > len(bs) {
                        loopMax = len(as)
                }
                for i := 0; i < loopMax; i++ { 
                        var x, y string
                        if len(as) > i {
                                x = as[i]
                        }
                        if len(bs) > i {
                                y = bs[i]
                        }
                        xi,_ := strconv.Atoi(x)
                        yi,_ := strconv.Atoi(y)
                        if xi > yi {
                                ret = -1
                        } else if xi < yi {
                                ret = 1
                        }
                        if ret != 0 {
                                break
                        }
                }       
                return 
        }
    

    http://play.golang.org/p/AetJqvFc3B

    0 讨论(0)
提交回复
热议问题