GoLang: Command Line Tool to Sort Strings


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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)
    }
}
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:

1
2
3
4
5
6
7
8
$ go run sort.go
aaa
ccc
bbb
Ctrl + D
aaa
bbb
ccc
$ go run sort.go
aaa
ccc
bbb
Ctrl + D
aaa
bbb
ccc

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
207 words
Last Post: Teaching Kids Programming - First Unique Character in a String
Next Post: Teaching Kids Programming - Determine a Armstrong Number

The Permanent URL is: GoLang: Command Line Tool to Sort Strings

Leave a Reply