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
+23.4k Find and replace a character in a string in Go
+8.5k Golang : How to join strings?
+8.7k Golang : Populate or initialize struct with values example
+9.3k Golang : How to extract video or image files from html source code
+28.3k Get file path of temporary file in Go
+13.8k Golang: Pad right or print ending(suffix) zero or spaces in fmt.Printf example
+7.2k Golang : Hue, Saturation and Value(HSV) with OpenCV example
+29.5k Golang : Get time.Duration in year, month, week or day
+16.1k Golang :Trim white spaces from a string
+7.6k Golang : Example of how to detect which type of script a word belongs to
+11.9k Golang : convert(cast) string to integer value