Golang : Sort and reverse sort a slice of strings
Sometimes we will want to sort or reverse sort a collection of strings alphabetically. It is pretty easy to sort a slice of strings in Go. Just declare the slice as type sort.StringSlice
and use the Sort
method.
Here’s an example of sorting slice of Strings in Go.
package main
import (
"fmt"
"sort"
)
var strSlice sort.StringSlice = []string{"apple", "durian", "kiwi", "banana"}
func main() {
fmt.Println("Original : ", strSlice[:])
strSlice.Sort()
fmt.Println("Sort : ", strSlice[:])
sort.Sort(sort.Reverse(strSlice[:]))
fmt.Println("Reverse : ", strSlice[:])
}
Output :
Original : [apple durian kiwi banana]
Sort : [apple banana durian kiwi]
Reverse : [kiwi durian banana apple]
See also : Golang : Sort and reverse sort a slice of integers
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+12.2k Elastic Search : Return all records (higher than default 10)
+11.2k Golang : Format numbers to nearest thousands such as kilos millions billions and trillions
+15.4k Golang : How to convert(cast) IP address to string?
+7.2k Golang : Check to see if *File is a file or directory
+7.5k Golang : get the current working directory of a running program
+8.5k Golang : How to join strings?
+8.6k Yum Error: no such table: packages
+16.9k Golang : Find file size(disk usage) with filepath.Walk
+62.4k Golang : Convert HTTP Response body to string
+5.7k Golang : Use NLP to get sentences for each paragraph example
+14.6k Golang : How to check for empty array string or string?
+3.9k Detect if Google Analytics and Developer Media are loaded properly or not