golang - how to sort string or []byte?

34,783

Solution 1

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)
}

Solution 2

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

Solution 3

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)

Solution 4

package main
import (
    "fmt"
    "sort"
)
func main() {
    word := "1àha漢字Pépy5"
    charArray := []rune(word)
    sort.Slice(charArray, func(i int, j int) bool {
        return charArray[i] < charArray[j]
    })
    fmt.Println(string(charArray))
}

Output:

15Pahpyàé字漢

Playground

Share:
34,783
leiyonglin
Author by

leiyonglin

求移民

Updated on October 22, 2021

Comments

  • leiyonglin
    leiyonglin over 2 years

    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.

    Thanks.