doujiao1180
doujiao1180
2016-02-08 18:48

在Go中比较长度不相等的字符串

已采纳

When I compare the following not equal length strings in Go, the result of comparison is not right. Can someone help?

i := "1206410694"
j := "128000000"
fmt.Println("result is", i >= j, i, j )

The output is:

result is false 1206410694 128000000

The reason is probably because Go does char by char comparison starting with the most significant char. In my case these strings represent numbers so i is larger than j. So just wonder if someone can help with explaining how not equal length strings are compared in go.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dongyupan4850 dongyupan4850 5年前

    The reason is probably because Go does char by char comparison starting with the most significant char.

    This is correct.

    If they represent numbers, then you should compare as them as numbers. Parse / convert them to int before comparing:

    ii, _ := strconv.Atoi(i)
    ij, _ := strconv.Atoi(j)
    

    Edit: And yes, @JimB is totally right. If you are not 100% sure that the conversion will succeed, please do not ignore the errors.

    点赞 评论 复制链接分享

相关推荐