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

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 中如何比较不等长的字符串。

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

这是正确的。

如果它们代表数字,那么您应该将它们作为数字进行比较。在比较之前将它们解析/转换为 int

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

编辑: 是的,@JimB 完全正确。如果您不能 100% 确定转换会成功,请不要忽略这些错误。