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
+22.1k Golang : Use TLS version 1.2 and enforce server security configuration over client
+9.4k Golang : Temperatures conversion example
+38.2k Golang : Read a text file and replace certain words
+31.8k Golang : How to convert(cast) string to IP address?
+20.9k Golang : Underscore or snake_case to camel case example
+15.3k JavaScript/JQuery : Detect or intercept enter key pressed example
+9.3k Golang : Generate Codabar
+8.4k Golang : Configure Apache and NGINX to access your Go service example
+5.9k Golang : Launching your executable inside a console under Linux
+17.8k Golang : Read data from config file and assign to variables
+13.8k Golang : Tutorial on loading GOB and PEM files