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
+13.6k Golang : Strings comparison
+35.4k Golang : Strip slashes from string example
+11.6k Golang : Change date format to yyyy-mm-dd
+22.4k Golang : Convert seconds to minutes and remainder seconds
+10k Golang : Translate language with language package example
+18.6k Golang : Aligning strings to right, left and center with fill example
+5.8k Linux : Disable and enable IPv4 forwarding
+8.5k Golang : How to check if input string is a word?
+8.9k Golang : Get final balance from bit coin address example
+8.7k Golang : Progress bar with ∎ character
+6.3k Golang : Process non-XML/JSON formatted ASCII text file example