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

huangapple go评论83阅读模式
英文:

Comparing not equal length strings in Go

问题

当我在Go语言中比较以下长度不相等的字符串时,比较的结果不正确。有人可以帮忙吗?

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

输出结果为:

result is false 1206410694 128000000

原因可能是因为Go语言按照字符逐个比较,从最高有效位开始比较。在我的情况下,这些字符串表示数字,所以i大于j。所以我想知道有人能否解释一下在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

得分: 4

原因可能是因为Go语言从最高有效位开始逐个字符比较。

这是正确的。

如果它们表示数字,那么在比较之前应该将它们解析/转换为int类型:

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

编辑: 是的,@JimB是完全正确的。如果你不能百分之百确定转换会成功,请不要忽略错误。

英文:

> 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.

huangapple
  • 本文由 发表于 2016年2月9日 02:48:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/35277022.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定