main.go 948 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package main
  2. import (
  3. "bufio"
  4. "flag"
  5. "fmt"
  6. "io"
  7. "os"
  8. )
  9. func main() {
  10. // Define a boolean flag -l to count lines instead of words
  11. lines := flag.Bool("l", false, "count lines")
  12. // Define a boolean flag -b to count bytes instead of words
  13. bytes := flag.Bool("b", false, "count bytes")
  14. // Parse the flags provided by the user
  15. flag.Parse()
  16. // Calling the count function to count the number of words (or lines)
  17. // received from the standard input and printing it out
  18. fmt.Println(count(os.Stdin, *lines, *bytes))
  19. }
  20. func count(r io.Reader, countLines bool, countBytes bool) int {
  21. scanner := bufio.NewScanner(r)
  22. if !countLines {
  23. if countBytes {
  24. scanner.Split(bufio.ScanBytes)
  25. } else {
  26. // Split sets the split function for the Scanner.
  27. // The default split function is ScanLines.
  28. scanner.Split(bufio.ScanWords)
  29. }
  30. }
  31. wc := 0
  32. // For every word scanned, increment the counter
  33. for scanner.Scan() {
  34. wc++
  35. }
  36. return wc
  37. }