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
+17.2k Golang : Fix cannot convert buffer (type *bytes.Buffer) to type string error
+7.6k Golang : How to detect if a sentence ends with a punctuation?
+10.8k Golang : Get local time and equivalent time in different time zone
+18k Golang : How to make a file read only and set it to writable again?
+14.7k Golang : Missing Bazaar command
+20.3k Golang : Count number of digits from given integer value
+14.7k Golang : How to check if your program is running in a terminal
+22.5k Golang : Convert seconds to minutes and remainder seconds
+10.4k Golang : Random Rune generator
+12.8k Golang : Get absolute path to binary for os.Exec function with exec.LookPath
+14.6k Golang : How to determine if user agent is a mobile device example