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
+13.1k Golang : How to determine if user agent is a mobile device example
+4.4k Golang : Generate Interleaved 2 inch by 5 inch barcode
+15.6k Golang : Get input from keyboard
+12k CodeIgniter : "Fatal error: Cannot use object of type stdClass as array" message
+16.3k Golang : Login and logout a user after password verification and redirect example
+17k Golang : Iterating Elements Over A List
+7.9k Golang : Intercept and compare HTTP response code example
+17.6k Golang : Get host name or domain name from IP address
+12.7k Golang : Fix cannot use buffer (type bytes.Buffer) as type io.Writer(Write method has pointer receiver) error
+4.6k How to check with curl if my website or the asset is gzipped ?
+27.9k Golang : JQuery AJAX post data to server and send data back to client example
+18.1k Golang : How to run your code only once with sync.Once object