Golang程序 对字符串进行排序

Golang程序 对字符串进行排序

Golang中的字符串是一个字符的集合。由于Go中的字符串是不可改变的,所以在产生后不能修改。然而,串联或添加到现有的字符串中,可以创建新的字符串。作为Go中的一个内置类型,字符串类型可以以各种方式使用,就像其他的数据类型一样。在这篇文章中,我们将通过不同的例子来学习不同的技术来对字符串进行排序。

语法

func Split(str, sep string) []string
Go

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

func Strings(src []string) []string
Go

strings函数被定义在sort包中。这个函数接收我们希望进行排序的字符串格式的数组,并通过对该数组进行排序返回结果。

算法

  • 第1步 – 创建一个包main并声明fmt(format包)、sort和strings包。

  • 第2步 – 启动主函数

  • 第 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
}
Go

输出

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

实例2

在这个例子中,我们将看到如何使用sort.Slice函数对一个字符串进行排序。在这里,未排序的字符串将被转换为符文,并作为输入传给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
}
Go

输出

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

例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
}
Go

输出

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

结论

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册