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
+9.6k Golang : Generate random elements without repetition or duplicate
+25.8k Golang : Record voice(audio) from microphone to .WAV file
+8.5k Golang : Resumable upload to Google Drive(RESTful) example
+10.9k Golang : 2 dimensional array example
+3.5k Adding Skype actions such as call and chat into web page examples
+16.5k Golang : Get all upper case or lower case characters from string example
+8.9k Golang : Print how to use flag for your application example
+4.7k Unix/Linux : How to test user agents blocked successfully ?
+30.9k Golang : How to check if a date is within certain range?
+4.7k Cash Flow : 50 days to pay your credit card debt
+18.8k Golang : Count number of digits from given integer value