Golang : Sort lines of text example
Here is an example of how to convert lines of text into a slice in Golang, sort them in descending order and then display the sorted output. Can be handy when you need to sort unstructured text data before processing further.
Here you go!
package main
import (
"fmt"
"sort"
"strings"
)
func sortLines(input string) string {
var sorted sort.StringSlice
sorted = strings.Split(input, "\n") // convert to slice
// just for fun
//fmt.Println("Sorted: ", sort.StringsAreSorted(sorted))
sorted.Sort()
//fmt.Println("Sorted: ", sort.StringsAreSorted(sorted))
return strings.Join(sorted, "\n")
}
func main() {
text := `stu
xyz
def
abc`
fmt.Println("Before: ", text)
fmt.Println("====================================")
fmt.Println("After: ", sortLines(text))
}
Before: stu
xyz
def
abc
====================================
After: abc
def
stu
xyz
See also : Golang : Sort and reverse sort a slice of strings
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
+28k Golang : Connect to database (MySQL/MariaDB) server
+23.3k Golang : Read a file into an array or slice example
+9.7k Golang : ffmpeg with os/exec.Command() returns non-zero status
+20.1k Swift : Convert (cast) Int to int32 or Uint32
+14.1k Elastic Search : Mapping date format and sort by date
+17.9k Golang : Check if a directory exist or not
+7.4k Golang : Dealing with struct's private part
+21.1k Golang : How to get time zone and load different time zone?
+12.8k Golang : Get terminal width and height example
+8.9k Golang : Get SPF and DMARC from email headers to fight spam
+18.7k Golang : Delete duplicate items from a slice/array
+8.8k Golang : Gaussian blur on image and camera video feed examples