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
+5.6k Golang : When to use make or new?
+8.9k Golang : Random Rune generator
+4.8k Get website traffic ranking with Similar Web or Alexa
+9.5k Golang : Get UDP client IP address and differentiate clients by port number
+31.2k Golang : Regular Expression for alphanumeric and underscore
+9.1k Golang : Convert file content to Hex
+5k Golang : Compound interest over time example
+5.4k Grep : How to grep for strings inside binary data
+4.6k Unix/Linux/MacOSx : Get local IP address
+5.1k Golang : Dealing with backquote
+27.7k Golang : How to create new XML file ?
+5.1k Golang : Get missing location after unmarshal binary and gob decode time.