Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang - how to sort string or []byte?

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.

like image 874
leiyonglin Avatar asked Mar 27 '14 13:03

leiyonglin


People also ask

How do I sort a string in go?

To sort a slice of strings in Go programming, use sort package. sort package offers sorting for builtin datatypes and user defined datatypes, through which we can sort a slice of strings. The sorting or strings happen lexicographically. Meaning a is less than b , b is less than c , and so on.

How do you sort an array in ascending order in Golang?

You simply pass an anonymous function to the sort. Slice function. This will sort in ascending order, if you want the opposite, simply write a[i] > a[j] in the anonymous function.

How sort Slice works in Golang?

In Go language, you can sort a slice with the help of Slice() function. This function sorts the specified slice given the provided less function. The result of this function is not stable. So for stable sort, you can use SliceStable.


3 Answers

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)
}
like image 115
deft_code Avatar answered Oct 07 '22 21:10

deft_code


You can convert the string to a slice of strings, sort it, and then convert it back to a string:

package main

import (
    "fmt"
    "sort"
    "strings"
)

func SortString(w string) string {
    s := strings.Split(w, "")
    sort.Strings(s)
    return strings.Join(s, "")
}

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

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

This prints:

bcad
abcd

Try it: http://play.golang.org/p/_6cTBAAZPb

like image 38
Fernando Á. Avatar answered Oct 07 '22 22:10

Fernando Á.


there is a simple way by leveraging function sort.Slice:

package main

import (
    "fmt"
    "sort"
)

func main() {
    word := "1BCagM9"
    s := []rune(word)
    sort.Slice(s, func(i int, j int) bool { return s[i] < s[j] })
    fmt.Println(string(s))
}

(Playground)

like image 27
nullne Avatar answered Oct 07 '22 22:10

nullne