sina February 2016

Comparing not equal length strings in 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.

Answers


TheHippo February 2016

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.

Post Status

Asked in February 2016
Viewed 2,668 times
Voted 5
Answered 1 times

Search




Leave an answer