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.2k Golang : Get Alexa ranking data example
+12.8k Golang : How to determine if a year is leap year?
+9.7k Golang : Underscore string example
+6.5k Golang : Calculate how many weeks left to go in a given year
+12.2k Generate salted password with OpenSSL example
+4.7k PHP : Convert CSV to JSON with YQL example
+12.5k Golang : Image to ASCII art example
+17.6k Golang : Generate thumbnails from images
+9.4k Golang : cannot assign type int to value (type uint8) in range error
+10.2k Golang : Intercept and process UNIX signals example
+11.4k Golang : Get month name from date example
+7k Golang : get the current working directory of a running program