sort

Golang 按字符串长度对 slice 排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package main

import (
	"fmt"
	"sort"
)

func main() {
	animals := []string{"snail", "dog", "cow", "elephant", "chicken", "mouse"}
	fmt.Println(animals)

	sort.Strings(animals) // 按 byte 排序
	fmt.Println(animals)

	sort.Slice(animals, func(i, j int) bool {
		return len(animals[i]) < len(animals[j]) // 按字符串长度 升序 排列
	})
	fmt.Println(animals)

	sort.Slice(animals, func(i, j int) bool {
		return len(animals[i]) > len(animals[j]) // 按字符串长度 降序 排列
	})
	fmt.Println(animals)
}

输出

1
2
3
4
[snail dog cow elephant chicken mouse]
[chicken cow dog elephant mouse snail]
[cow dog mouse snail chicken elephant]
[elephant chicken mouse snail cow dog]

本文网址: https://golangnote.com/topic/299.html 转摘请注明来源