Golang对中文汉字进行拼音排序

sort.Strings排序默认是按照Unicode码点的顺序的。

如果需要按照拼音排序, 可以通过GBK转换实现, 自定义一个排序接口, 这里的排序优先级 数字>字母>汉字

代码如下:

package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "sort"

    "golang.org/x/text/encoding/simplifiedchinese"
    "golang.org/x/text/transform"
)

type Animal struct {
	Id   int
	Name string
	Age  int
}
type Animals []Animal

func (a Animals) Len() int { return len(a) }
func (s Animals) Less(i, j int) bool {
	a, _ := UTF82GBK(s[i].Name)
	b, _ := UTF82GBK(s[j].Name)
	bLen := len(b)
	for idx, chr := range a {
		if idx > bLen-1 {
			return false
		}
		if chr != b[idx] {
			return chr < b[idx]
		}
	}
	return true
}
func (a Animals) Swap(i, j int) { a[i], a[j] = a[j], a[i] }

//UTF82GBK : transform UTF8 rune into GBK byte array
func UTF82GBK(src string) ([]byte, error) {
	GB18030 := simplifiedchinese.All[0]
	return ioutil.ReadAll(transform.NewReader(bytes.NewReader([]byte(src)), GB18030.NewEncoder()))
}

//GBK2UTF8 : transform  GBK byte array into UTF8 string
func GBK2UTF8(src []byte) (string, error) {
	GB18030 := simplifiedchinese.All[0]
	bytes, err := ioutil.ReadAll(transform.NewReader(bytes.NewReader(src), GB18030.NewDecoder()))
	return string(bytes), err
}

func main() {
    an := Animals{
		Animal{Id: 1, Name: "请求", Age: 11},
		Animal{Id: 2, Name: "当当", Age: 22},
		Animal{Id: 3, Name: "呃呃", Age: 33},
		Animal{Id: 4, Name: "z奥啊", Age: 44},
		Animal{Id: 5, Name: "宝宝z", Age: 55},
		Animal{Id: 6, Name: "宝宝a", Age: 6},
	}

    sort.Sort(an)
    fmt.Println(an)
    //[{4 z奥啊 44} {6 宝宝a 6} {5 宝宝z 55} {2 当当 22} {1 请求 11} {3 呃呃 33}]
}
发布了264 篇原创文章 · 获赞 23 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/Edu_enth/article/details/99863739
今日推荐