英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论