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.4k Android Studio : Hello World example
+6.5k Golang : Set or add headers for many or different handlers
+5.9k Setting $GOPATH environment variable for Unix/Linux and Windows
+5.2k Golang : What fmt.Println() can do and println() cannot do
+6.8k Golang : Get SPF and DMARC from email headers to fight spam
+6.4k Golang : How to check variable or object type during runtime?
+6.4k Golang : Another camera capture GUI application with GTK and OpenCV
+15.4k Golang : Get current URL example
+8.3k Golang : How to delete element(data) from map ?
+6.2k Golang : Oanda bot with Telegram and RSI example
+17.7k Golang : GORM create record or insert new record into database example
+11.6k Golang : Save(pipe) HTTP response into a file