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
+4.9k Unix/Linux : How to test user agents blocked successfully ?
+4.6k PHP : Convert string to timestamp or datestamp before storing to database(MariaDB/MySQL)
+13.4k Golang : Parsing or breaking down URL
+5.2k Golang : Dealing with backquote
+9.7k Golang : Fix go.exe is not compatible with the version of Windows you're running
+22.9k Golang : Find biggest/largest number in array
+18.4k Golang : Check if os.Stdin input data is piped or from terminal
+10k Golang : Delay or limit HTTP requests example
+8.3k Golang : Scramble and unscramble text message by randomly replacing words
+10.7k Golang : How to detect a server/machine network interface capabilities?
+18.4k Golang : Close channel after ticker stopped example
+24k Golang : Convert uint value to string type