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
+11.4k Golang : How to use if, eq and print properly in html template
+28.3k Golang : Connect to database (MySQL/MariaDB) server
+16.8k Golang : Gzip file example
+11.8k Golang : Display a text file line by line with line number example
+23.9k Find and replace a character in a string in Go
+12.3k Golang : Split strings into command line arguments
+18.1k Golang : Qt image viewer example
+10.8k Golang : Interfacing with PayPal's IPN(Instant Payment Notification) example
+10.3k Golang : Find and replace data in all files recursively
+28.8k Golang : Read, Write(Create) and Delete Cookie example
+12.3k Golang : md5 hash of a string
+88.4k Golang : How to convert character to ASCII and back