0

I passed few hours searching about a lib or a way to do this:

I have an array []string{"ex10", "ex2", "ex1"} and after call the sort.Strings or using sort.Slice to compare with an array of bytes I get the result []string{"ex1", "ex10", "ex2"}

anyone has an idea how to implement this?

if anyone knows swift I've found the solution here

2
  • 3
    This is called natural sort: golanglibs.com/search?q=natural+sort Commented Jan 11, 2019 at 23:15
  • To add to the other comments/answers, I would recommend to avoid this kind of data for sorting. Normalize it with leading zeros instead. The problem is that you'll run into all kinds of corner cases unless your problem is simple - JimB's answer assumes a certain format and will fail for others, for example. It's often worthwhile to clean up your data instead of bending backwards to process it Commented Jan 12, 2019 at 13:29

1 Answer 1

3

If you don't want the numbers sorted lexicographically, you need to separate them from the strings and parse them as integers.

This example assumes there is always a 2 letter prefix with a valid number, and slices the string accordingly: https://play.golang.org/p/LaX-pTr6etc

s := []string{"ex10", "ex2", "ex1"}

sort.Slice(s, func(i, j int) bool {
    if s[i][:2] != s[j][:2] {
        return s[i] < s[j]
    }
    ii, _ := strconv.Atoi(s[i][2:])
    jj, _ := strconv.Atoi(s[j][2:])
    return ii < jj
})
Sign up to request clarification or add additional context in comments.

Comments

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.