How to compare two version number strings in golang

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

提交回复
热议问题