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
+21.3k Golang : For loop continue,break and range
+5.8k Python : Print unicode escape characters and string
+7k Golang : Get expvar(export variables) to work with multiplexer
+27k Golang : Convert file content into array of bytes
+26.9k Golang : How to check if a connection to database is still alive ?
+11.2k Golang : Replace a parameter's value inside a configuration file example
+25.6k Golang : Convert long hexadecimal with strconv.ParseUint example
+6.1k Golang : Generate multiplication table from an integer example
+6k Golang : Detect variable or constant type
+16.8k Golang : Delete files by extension
+26.1k Golang : Daemonizing a simple web server process example
+7k Golang : Muxing with Martini example