golang – how to sort string or []byte?

Issue

I am looking for a function, that can sort string or []byte:

"bcad" to "abcd"
or
[]byte("bcad") to []byte("abcd")

The string only contains letters – but sorting should also work for letters and numbers.

I found sort package but not the function I want.

Solution

It feels wasteful to create a string for each character just to Join them.

Here’s one that is a little less wasteful, but with more boiler plate. playground://XEckr_rpr8

type sortRunes []rune

func (s sortRunes) Less(i, j int) bool {
    return s[i] < s[j]
}

func (s sortRunes) Swap(i, j int) {
    s[i], s[j] = s[j], s[i]
}

func (s sortRunes) Len() int {
    return len(s)
}

func SortString(s string) string {
    r := []rune(s)
    sort.Sort(sortRunes(r))
    return string(r)
}

func main() {
    w1 := "bcad"
    w2 := SortString(w1)

    fmt.Println(w1)
    fmt.Println(w2)
}

Answered By – deft_code

Answer Checked By – David Marino (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.