golang - how to sort string or []byte?
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)
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)
}
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