[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:
- Convert string to []rune
- Define a new type ByRune, which is actually []rune. Implement Len, Swap, and Less methods of type ByRune.
- Call sort.Sort to sort the slice of runes.
- Convert []rune back to string and return the string.
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:
- Convert string to []rune
- Define a less method and call sort.Slice with the slice of runes and the less method as parameters.
- Convert []rune back to string and return the string.
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:
- Ubuntu Linux 17.04, Go 1.8.1
- Go Playground
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 |