-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
48 lines (38 loc) · 973 Bytes
/
main.go
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package main
import (
"bufio"
"flag"
"fmt"
"io"
"os"
)
func main() {
//defining the boolean flag -l to count lines instead of words
lines := flag.Bool("l", false, "Count lines")
bytes := flag.Bool("b", false, "Count bytes")
//parsing the flag provided by the user
flag.Parse()
//Calling the count function to count the number of words
//received ferom the standard input and printing it out
fmt.Println(count(os.Stdin, *lines, *bytes))
}
func count(r io.Reader, countLines bool, countBytes bool) int {
// a scanner is used to read a text from a reader (such as files)
scanner := bufio.NewScanner(r)
// define the scanner split type to words or bytes(default is split by line)
if !countLines {
if !countBytes {
scanner.Split(bufio.ScanWords)
} else {
scanner.Split(bufio.ScanBytes)
}
}
// define a counter
wc := 0
// for every word scanned, increment the counter
for scanner.Scan() {
wc++
}
//return the total
return wc
}