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
+6.4k Golang : Handling Yes No Quit query input
+5.4k Golang : Combine slices of complex numbers and operation example
+14.1k Golang : Get checkbox or extract multipart form data value example
+10.9k Golang : 2 dimensional array example
+14.8k Golang : Get IP addresses of a domain name
+20.5k Golang : How to reverse slice or array elements order
+6.6k Golang : How to execute code at certain day, hour and minute?
+14k Golang : Get query string value on a POST request
+29.1k Golang : How to redirect to new page with net/http?
+11.3k Golang : How to calculate the distance between two coordinates using Haversine formula
+21.5k Golang : Calculate time different
+8.4k Golang : How to protect your source code from client, hosting company or hacker?