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
+16.9k Golang : Get number of CPU cores
+13.3k Golang : Get constant name from value
+25.3k Golang : Generate MD5 checksum of a file
+11.2k Golang : How to use if, eq and print properly in html template
+17.6k Golang : Read data from config file and assign to variables
+13.2k Golang : Linear algebra and matrix calculation example
+12.2k Golang : Print UTF-8 fonts on image example
+5.4k Gogland : Datasource explorer
+5k Golang : PGX CopyFrom to insert rows into Postgres database
+14.6k Golang : Get URI segments by number and assign as variable example
+13.9k Golang : concatenate(combine) strings
+9.7k Golang : interface - when and where to use examples