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
+12.4k Golang : Search and extract certain XML data example
+21.7k Golang : Encrypt and decrypt data with TripleDES
+7.7k Golang : Command line ticker to show work in progress
+13.3k Golang : Date and Time formatting
+10.6k Fix ERROR 1045 (28000): Access denied for user 'root'@'ip-address' (using password: YES)
+6.9k Swift : substringWithRange() function example
+6.1k Golang : Measure execution time for a function
+8.2k Golang : Metaprogramming example of wrapping a function
+29.2k Golang : missing Git command
+9.5k Golang : Qt Yes No and Quit message box example
+12.6k Golang : Arithmetic operation with numerical slices or arrays example
+5.4k Golang : How to deal with configuration data?