GoLang: Command Line Tool to Sort Strings

in #golang5 years ago

We can sort a list of given strings from stdin and output to stdout using the following GoLang:

package main

import (
    "fmt"
    "bufio"
    "os"
    "sort"
    "strings"
)

func main() {
    reader := bufio.NewReader(os.Stdin)
    var data = []string{}
    for true {
        s, _ := reader.ReadString('\n')
        s = strings.Trim(s, "\n")
        if len(s) == 0 {
            break
        }
        data = append(data, s)
    }
    sort.Strings(data)
    for _, a := range data {
        fmt.Println(a)
    }
}

The list of string data is constructed from os.Stdin line by line. And we call sort.Strings to sort them alphabetically in ascending order. Then we iterate over the sorted list and print them out to standard output.

For example:

$ go run sort.go
aaa
ccc
bbb
Ctrl + D
aaa
bbb
ccc

Reposted to Blog

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Thank you for reading ^^^^^^^^^^^^^^^

NEW! Following my Trail (Upvote or/and Downvote)

Follow me for topics of Algorithms, Blockchain and Cloud.
I am @justyy - a Steem Witness
https://steemyy.com

My contributions

Delegation Service

Important Update of Delegation Service!

  • Delegate 1000 to justyy: Link
  • Delegate 5000 to justyy: Link
  • Delegate 10000 to justyy: Link

Support me

If you like my work, please:

  1. Delegate SP: https://steemyy.com/sp-delegate-form/?delegatee=justyy
  2. Vote @justyy as Witness: https://steemyy.com/witness-voting/?witness=justyy&action=approve
  3. Set @justyy as Proxy: https://steemyy.com/witness-voting/?witness=justyy&action=proxy
    Alternatively, you can vote witness or set proxy here: https://steemit.com/~witnesses

Sort:  

Hello Sir

It was very Amazing ..

Coin Marketplace

STEEM 0.04
TRX 0.32
JST 0.085
BTC 60328.01
ETH 1579.98
USDT 1.00
SBD 0.42