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
+11.6k Golang : Find and draw contours with OpenCV example
+25.7k Mac/Linux and Golang : Fix bind: address already in use error
+11.1k Golang : Concatenate (combine) buffer data example
+13.8k Golang : Google Drive API upload and rename example
+14.4k Golang : Get URI segments by number and assign as variable example
+13.8k Golang : Simple word wrap or line breaking example
+13.1k Golang : Read from buffered reader until specific number of bytes
+5.3k PHP : Convert CSV to JSON with YQL example
+4.6k Javascript : How to get width and height of a div?
+8.3k Python : Fix SyntaxError: Non-ASCII character in file, but no encoding declared
+11.6k Golang : Convert(cast) bigint to string