1

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.

3
  • 4
    Strings are compared lexically. Do you want to compare the decimal numbers in the strings? Commented Feb 8, 2016 at 18:53
  • Yes, that's what I want Commented Feb 8, 2016 at 19:23
  • the length of two strings can be compared by getting the length of each string: len("string") Commented Feb 9, 2016 at 10:49

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

And don't forget to check the errors if you want to avoid accidentally comparing a non-number as 0.
Also this will fail if the number is to large to hold in an int64

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.