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.6k Golang : Convert word to its plural form example
+8.3k Golang : Setting variable value with ldflags
+16.7k Swift : Convert (cast) Int to int32 or Uint32
+20.9k Golang : Daemonizing a simple web server process example
+6.7k Golang : Metaprogramming example of wrapping a function
+14.8k Golang : How to run your code only once with sync.Once object
+21.5k Golang : Convert IP address string to long ( unsigned 32-bit integer )
+18.5k Golang : Convert seconds to minutes and remainder seconds
+13.6k Golang : Get IP addresses of a domain name
+3.1k Golang : Valued expressions and functions example
+8.2k Golang : Channels and buffered channels examples