2013年8月21日星期三

How to implement a simple word-count utility by scanning the input as a sequence of space-delimited tokens.

Use a Scanner to implement a simple word-count utility by scanning the input as a sequence of space-delimited tokens.

package main

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

func main() {
// An artificial input source.
const input = "Now is the winter of our discontent,\nMade glorious summer by this sun of York.\n"
scanner := bufio.NewScanner(strings.NewReader(input))
// Set the split function for the scanning operation.
scanner.Split(bufio.ScanWords)
// Count the words.
count := 0
for scanner.Scan() {
fmt.Println(scanner.Text())
count++
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading input:", err)
}
fmt.Printf("%d\n", count)
}

没有评论:

发表评论