Belajar Sorting a String and Write to File with Golang
Belajar sorting sebuah string dari argument terminal dan tulis ke sebuah file.
Expected Output:
go run main.go orange banana apple
cat sorted.txt apple banana orange
package main import ( "fmt" "io/ioutil" "os" "sort" ) func main() { // get all arguments items := os.Args[1:] if len(items) == 0 { fmt.Println("Send me some items and I will sort them") return } // String slices are sortable using `sort.Strings` sort.Strings(items) var data []byte for _, s := range items { // append a string to a byte slice data = append(data, s...) } err := ioutil.WriteFile("sorted.txt", data, 0644) if err != nil { fmt.Println(err) return } }
Output: