word_letter_count.go 804 B

12345678910111213141516171819202122232425262728293031323334353637
  1. // Q28_word_letter_count.go
  2. package main
  3. import (
  4. "bufio"
  5. "fmt"
  6. "os"
  7. "strings"
  8. )
  9. var nrchars, nrwords, nrlines int
  10. func main() {
  11. nrchars, nrwords, nrlines = 0, 0, 0
  12. inputReader := bufio.NewReader(os.Stdin)
  13. fmt.Println("Please enter some input, type S to stop: ")
  14. for {
  15. input, err := inputReader.ReadString('\n')
  16. if err != nil {
  17. fmt.Printf("An error occurred: %s\n", err)
  18. }
  19. if input == "S\r\n" { // Windows, on Linux it is "S\n"
  20. fmt.Println("Here are the counts:")
  21. fmt.Printf("Number of characters: %d\n", nrchars)
  22. fmt.Printf("Number of words: %d\n", nrwords)
  23. fmt.Printf("Number of lines: %d\n", nrlines)
  24. os.Exit(0)
  25. }
  26. Counters(input)
  27. }
  28. }
  29. func Counters(input string) {
  30. nrchars += len(input) - 2 // -2 for \r\n
  31. nrwords += len(strings.Fields(input))
  32. nrlines++
  33. }