汉语转拼音
库
go get -u github.com/mozillazg/go-pinyin
结构体
// 结构体
type ProductListView struct {
Id int `gorm:"primary_key;" json:"id"`
TradeBrand string `json:"trade_brand"`
TradeName string `json:"trade_name"`
FirstLetter string `json:"first_letter"` // 首字母
}
获取首字母
// 获取首字母
func GetFirstLetter(str string) string {
args := pinyin.NewArgs()
args.Style = pinyin.FIRST_LETTER
tradeBrand := strings.Replace(str, " ", "", -1)
a := pinyin.Pinyin(tradeBrand, args)
if len(a) > 0 {
return strings.ToUpper(a[0][0])
} else {
return strings.ToUpper(tradeBrand[:1])
}
}
算法实现
// 按照首字母 冒泡排序算法
func firstLetterSort(arr []ProductListView) []ProductListView {
length := len(arr)
for i := 0; i < length-1; i++ {
// 是否交换数据
flag := false
for j := 0; j < length-1-i; j++ {
// 相邻元素两两对比
if arr[j].FirstLetter > arr[j+1].FirstLetter {
// 元素交换
temp := arr[j+1]
arr[j+1] = arr[j]
arr[j] = temp
flag = true
}
}
if !flag {
break
}
}
return arr
}
欢迎关注微信公众号:【皮卡战记】
