In Go, you can sort characters in a string by converting the string to a slice of runes, sorting the slice, and then converting it back to a string.
In this example,
str
.[]rune(str)
.sort.Slice
with a custom comparator function.string()
conversion.package main
import (
"fmt"
"sort"
)
func main() {
str := "hello world"
runes := []rune(str)
sort.Slice(runes, func(i, j int) bool {
return runes[i] < runes[j]
})
sortedStr := string(runes)
fmt.Println("Sorted string in ascending order:", sortedStr)
}
Sorted string in ascending order: dehllloorw
In this example,
str
.[]rune(str)
.sort.Slice
with a custom comparator function.string()
conversion.package main
import (
"fmt"
"sort"
)
func main() {
str := "hello world"
runes := []rune(str)
sort.Slice(runes, func(i, j int) bool {
return runes[i] > runes[j]
})
sortedStr := string(runes)
fmt.Println("Sorted string in descending order:", sortedStr)
}
Sorted string in descending order: wroolllhed
In this tutorial, we learned How to Sort Characters in String in Go language with well detailed examples.