Reading lines in Go
bufio.Scanner walks a reader line by line, and its error needs checking.
func countLines(input string) (int, int, error) {
scanner := bufio.NewScanner(strings.NewReader(input))
scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
lines, words := 0, 0
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" {
continue
}
lines++
words += len(strings.Fields(line))
}
if err := scanner.Err(); err != nil {
return 0, 0, fmt.Errorf("scan: %w", err)
}
return lines, words, nil
}
How it works
Scanreturns false at the end or on an error.Errafterwards distinguishes the two.Bufferraises the limit for very long lines.
Keywords and builtins used here
bytecontinueerrorforfuncifintlenmakereturnstring
The run, in numbers
- Lines
- 18
- Characters to type
- 420
- Tokens
- 129
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 74 seconds.
Step 1 of 3 in Files & IO, step 6 of 26 in Standard library & project layout.