[Golang] Sort String by Character


Sort a string by character, i.e., convert the string to []rune and then sort the slice of runes in Go programming language. This problem is actually the same as sorting a slice of runes in nature.

We use sort package in Go standard library to help us sort []rune, converted from the string.

Go prior to 1.8

The steps:

  1. Convert string to []rune
  2. Define a new type ByRune, which is actually []rune. Implement Len, Swap, and Less methods of type ByRune.
  3. Call sort.Sort to sort the slice of runes.
  4. Convert []rune back to string and return the string.

Run Code on Go Playground

package main

import (
      "fmt"
      "sort"
)

type ByRune []rune

func (r ByRune) Len() int           { return len(r) }
func (r ByRune) Swap(i, j int)      { r[i], r[j] = r[j], r[i] }
func (r ByRune) Less(i, j int) bool { return r[i] < r[j] }

func StringToRuneSlice(s string) []rune {
      var r []rune
      for _, runeValue := range s {
              r = append(r, runeValue)
      }
      return r
}

func SortStringByCharacter(s string) string {
      var r ByRune = StringToRuneSlice(s)
      sort.Sort(r)
      return string(r)
}

func main() {
      fmt.Println(SortStringByCharacter("listen"))
      fmt.Println(SortStringByCharacter("silent"))
}

Go 1.8 or later

The sort package in Go 1.8 introduces new methods for sorting slices [6]. We can use sort.Slice method directly without defining a new type.

The steps:

  1. Convert string to []rune
  2. Define a less method and call sort.Slice with the slice of runes and the less method as parameters.
  3. Convert []rune back to string and return the string.

Run Code on Go Playground

package main

import (
      "fmt"
      "sort"
)

func StringToRuneSlice(s string) []rune {
      var r []rune
      for _, runeValue := range s {
              r = append(r, runeValue)
      }
      return r
}

func SortStringByCharacter(s string) string {
      r := StringToRuneSlice(s)
      sort.Slice(r, func(i, j int) bool {
              return r[i] < r[j]
      })
      return string(r)
}

func main() {
      fmt.Println(SortStringByCharacter("listen"))
      fmt.Println(SortStringByCharacter("silent"))
}

Tested on:


References:

[1]
[2]string - Go sort a slice of runes? - Stack Overflow
[3]Package sort - The Go Programming Language
[4][Golang] Check Whether Two Strings Are Anagram of Each Other
[5]Strings, bytes, runes and characters in Go - The Go Blog
[6]sort: make sorting easier, add Slice, SliceStable, SliceIsSorted, reflect.Swapper · Issue #16721 · golang/go · GitHub