Go: Count lines and words

A scanner lets a program read input of any length.

What to build

A program that reports simple statistics about its input text.

Requirements

  • Read lines until the input ends.
  • Print lines: L, words: W and longest: TEXT, where L is the number of lines (blank lines count), W is the number of words, and TEXT is the longest line (the first one if several have the same length).

Input

Any number of lines of text.

Output

Three lines.

Constraints

1 to 100 lines, each with at most 100 characters.

Example

Input:

the quick brown fox
jumps over

the lazy dog

Output:

lines: 4
words: 9
longest: the quick brown fox

Why it works

The scanner returns each line without its newline. strings.Fields counts words correctly even with extra spaces, and len(line) compares the lengths.

Examples

Example 1 · Input
the quick brown fox
jumps over

the lazy dog
Expected output
lines: 4
words: 9
longest: the quick brown fox
Example 2 · Input
hello
Expected output
lines: 1
words: 1
longest: hello

Hints

Hint 1

Use bufio.NewScanner(os.Stdin) and loop while scanner.Scan().

Hint 2

Keep the longest line so far; replace it only when a line is strictly longer.

Solution

Show one correct solution (try it yourself first)
package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	lines, words := 0, 0
	longest := ""
	for scanner.Scan() {
		line := scanner.Text()
		lines++
		words += len(strings.Fields(line))
		if len(line) > len(longest) {
			longest = line
		}
	}
	fmt.Println("lines:", lines)
	fmt.Println("words:", words)
	fmt.Println("longest:", longest)
}

▶ Open this solution in the compiler

Lesson: Reading input →