Go语言字符串排序程序


Go语言中的字符串是字符的集合。由于Go语言中的字符串是不可变的,因此一旦生成就不能修改。但是,可以通过连接或添加到现有字符串来创建新字符串。字符串类型是Go语言中内置的一种类型,可以像其他任何数据类型一样以多种方式使用。在本文中,我们将学习使用不同的示例来学习排序字符串的不同技术。

语法

func Split(str, sep string) []string

Split() 函数用于通过提供的分隔符分割字符串。此函数存在于 strings 包中,它接受要分割的字符串以及分隔符作为参数。然后,该函数返回最终的字符串数组作为结果。

func Strings(src []string) []string

strings 函数定义在 sort 包中。此函数接受我们希望排序的字符串格式的数组,并通过排序该数组返回结果。

算法

  • 步骤 1 - 创建一个 main 包并声明 fmt(格式包)、sort 和 strings 包

  • 步骤 2 - 启动 main 函数

  • 步骤 3 - 将字符串分割成单个字符

  • 步骤 4 - 使用内部函数对字符进行排序并将它们组合成字符串

  • 步骤 5 - 打印输出

示例 1

在这个例子中,我们将使用 sort.Slice 函数对未排序的字符串进行排序。控制台打印的输出将是一个已排序的字符串。让我们通过代码和算法了解如何执行此程序。

package main
import (
   "fmt"
   "sort" //import fmt and sort package
)

//create main function to execute the program
func main() {
   unsorted_str := "ghfisaw" //create unsorted string
   fmt.Println("The unsorted string is:", unsorted_str)
   chars := []rune(unsorted_str)
   sort.Slice(chars, func(i, j int) bool { //sort the string using the function
      return chars[i] < chars[j]
   })
   fmt.Println("The sorted string is:")
   fmt.Println(string(chars)) //print the string on the console
}

输出

The unsorted string is: ghfisaw
The sorted string is:
afghisw

示例 2

在这个例子中,我们将看到如何使用 sort.Slice 函数对字符串进行排序。这里,未排序的字符串将被转换为 rune,并将其作为输入传递到 sort.Slice 函数中以对字符串进行排序。

package main
import (
   "fmt"
   "sort" //import fmt and sort package
)

//create a main function to execute the program
func main() {
   unsorted_str := "dbl" //create an unsorted string
   fmt.Println("The unsorted string created here is:", unsorted_str)
   strrunes := []rune(unsorted_str) //convert the string to rune
   sort.Slice(strrunes, func(i, j int) bool {
      return strrunes[i] < strrunes[j] //sort the string rune
   })
   fmt.Println("The sorted string is:")
   fmt.Println(string(strrunes)) //print sorted string
}

输出

The unsorted string created here is: dbl
The sorted string is:
bdl

示例 3

在这个例子中,我们将使用 strings.split 函数和 sort.Strings 对字符串进行排序。前者用于分割字符,后者用于对字符进行排序。输出将使用 fmt.Println() 函数打印到控制台。

package main
import (
   "fmt"
   "sort"
   "strings" //import fmt, sort and strings package
)

//create a main function to execute the program
func main() {
   unsorted_str := "kertgld" //create an unsorted string
   fmt.Println("The unsorted string created here is:", unsorted_str)
   chars := strings.Split(unsorted_str, "") //split the string into characters
   sort.Strings(chars) //sort the characters
   fmt.Println("The sorted string formed here is:")
   fmt.Println(strings.Join(chars, "")) //join the characters and print on console
}

输出

The unsorted string created here is: kertgld
The sorted string formed here is:
degklrt

结论

我们分别用三个例子执行了字符串排序程序。在第一个例子中,我们使用了 sort.Slice() 函数对字符串进行排序;在第二个例子中,我们将未排序的字符串转换为 rune,然后对其应用 sort.Slice() 函数;在第三个例子中,我们使用了 sort.strings 和 strings.split 函数,其中字符串被分割,然后根据字符进行排序。因此,程序成功执行。

更新于:2023年2月13日

5K+ 浏览量

开启您的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.