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
+6.1k Golang : Get environment variable
+12.2k Golang : reCAPTCHA example
+32.7k Golang : convert(cast) bytes to string
+20.7k Golang : Print leading(padding) zero or spaces in fmt.Printf?
+8.9k Golang : Get current, epoch time and display by year, month and day
+7.5k Golang : Another camera capture GUI application with GTK and OpenCV
+7.8k Golang : Get final balance from bit coin address example
+12.7k Golang : Gin framework accept query string by post request example
+5.1k AWS S3 : Prevent Hotlinking policy
+5k Golang : List all packages and search for certain package
+20k Golang : Encrypt and decrypt data with TripleDES
+6.7k Setting $GOPATH environment variable for Unix/Linux and Windows