Golang 如何对字符串的片断进行排序
在Go语言中,slice比数组更加强大、灵活、方便,是一种轻量级的数据结构。slice是一个可变长度的序列,它存储相似类型的元素,你不允许在同一个slice中存储不同类型的元素。Go语言允许你根据其类型对片断的元素进行排序。因此,一个字符串类型的片断可以通过使用以下函数进行排序。这些函数是在sort包中定义的,所以你必须在你的程序中导入sort包来访问这些函数。
1.字符串: 该函数仅用于对字符串片断进行排序,它对片断中的元素按递增顺序进行排序。
语法
func Strings(scl []string)
这里,slc代表字符串的一个片断。让我们借助于一个例子来讨论这个概念。
例子
// Go program to illustrate how
// to sort the slice of strings
package main
import (
"fmt"
"sort"
)
// Main function
func main() {
// Creating and initializing slices
// Using shorthand declaration
scl1 := []string{"abc", "rwp", "def", "por", "ber", "erj"}
scl2 := []string{"Rabbit", "Fish", "Dog",
"Parrot", "Cat", "Hamster"}
// Displaying slices
fmt.Println("Slices(Before):")
fmt.Println("Slice 1: ", scl1)
fmt.Println("Slice 2: ", scl2)
// Sorting the slice of strings
// Using Strings function
sort.Strings(scl1)
sort.Strings(scl2)
// Displaying the result
fmt.Println("\nSlices(After):")
fmt.Println("Slice 1 : ", scl1)
fmt.Println("Slice 2 : ", scl2)
}
输出
Slices(Before):
Slice 1: [abc rwp def por ber erj]
Slice 2: [Rabbit Fish Dog Parrot Cat Hamster]
Slices(After):
Slice 1 : [abc ber def erj por rwp]
Slice 2 : [Cat Dog Fish Hamster Parrot Rabbit]
2.StringsAreSorted: 该函数用于检查给定的字符串片断是否为排序形式(按递增顺序)。如果该片段处于排序状态,则该方法返回true;如果该片段不处于排序状态,则返回false。
语法
func StringsAreSorted(scl []string) bool
这里,scl代表字符串的一个片断。让我们借助于一个例子来讨论这个概念。
例子
// Go program to illustrate how to check
// whether the given slice of strings
// is in sorted form or not
package main
import (
"fmt"
"sort"
)
// Main function
func main() {
// Creating and initializing slices
// Using shorthand declaration
scl1 := []string{"abc", "ber", "def", "erj", "por", "rwp"}
scl2 := []string{"Rabbit", "Fish", "Dog",
"Parrot", "Cat", "Hamster"}
// Displaying slices
fmt.Println("Slices:")
fmt.Println("Slice 1: ", scl1)
fmt.Println("Slice 2: ", scl2)
// Checking the slice is in sorted form or not
// Using StringsAreSorted function
res1 := sort.StringsAreSorted(scl1)
res2 := sort.StringsAreSorted(scl2)
// Displaying the result
fmt.Println("\nResult:")
fmt.Println("Is Slice 1 is sorted?: ", res1)
fmt.Println("Is Slice 2 is sorted?: ", res2)
}
输出
Slices:
Slice 1: [abc ber def erj por rwp]
Slice 2: [Rabbit Fish Dog Parrot Cat Hamster]
Result:
Is Slice 1 is sorted?: true
Is Slice 2 is sorted?: false
极客教程