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
+8.1k Golang : Play .WAV file from command line
+10.6k Linux : How to install driver for 600Mbps Dual Band Wifi USB Adapter
+8k Golang : Detect Pascal, Kebab, Screaming Snake and Camel cases
+6.1k Golang : Array mapping with Interface
+6k Golang : How to detect if a sentence ends with a punctuation?
+37.8k Golang : Remove dashes(or any character) from string
+27.9k Golang : JQuery AJAX post data to server and send data back to client example
+11.6k Golang : Transform comma separated string to slice example
+9.7k Golang : Simple image viewer with Go-GTK
+10k Golang : Fix fmt.Scanf() on Windows will scan input twice problem
+18.2k Golang : Measure http.Get() execution time
+18.7k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it