概述
在 Golang 中,字符串是一个字节序列。一个字符串字面意思实际上代表了一个UTF-8的字节序列。在UTF-8中,ASCII字符是单字节的,对应于前128个Unicode字符。所有其他字符都在1-4字节之间。为了更好地理解它,请看下面这个字符串
sample := "a£c"
在上述字符串中
-
根据UTF-8,'a'需要一个字节。
-
'£'按UTF-8标准需要两个字节
-
b'按UTF-8标准需要一个字节。
上述字符串总共有1+2+1=4个字节。因此,当我们试图用标准的**len()函数来打印字符串的长度时,它将输出4而不是3,因为len()**函数返回的是字符串中的字节数。
fmt.Printf("Length is %d\n", len(sample))
因此,为了对字符串进行排序,我们需要将其转换为一个符文数组,然后使用go的sort.Sort函数对其进行排序。
下面是**sort.**Sort函数的签名
func Sort(data Interface)
其中,这是接口的定义
type Interface interface {
// Len is the number of elements in the collection.
Len() int
// Less reports whether the element with index i
// must sort before the element with index j.
Less(i, j int) bool
// Swap swaps the elements with indexes i and j.
Swap(i, j int)
}
因此,无论我们想用sort.Sort函数进行排序,都需要实现以上三个函数
-
Len() int
-
Less(i, j int) bool
-
Swap(i, j int)
在下面的程序中,我们做了同样的事情
package main
import (
"fmt"
"sort"
)
func main() {
sortString("bac")
}
func sortString(input string) {
runeArray := []rune(input)
sort.Sort(sortRuneString(runeArray))
fmt.Println(string(runeArray))
}
type sortRuneString []rune
func (s sortRuneString) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s sortRuneString) Less(i, j int) bool {
return s[i] < s[j]
}
func (s sortRuneString) Len() int {
return len(s)
}
输出
abc