Skip to content

Instantly share code, notes, and snippets.

@caelifer
Last active September 18, 2015 22:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caelifer/4e34564adb3e891facc7 to your computer and use it in GitHub Desktop.
Save caelifer/4e34564adb3e891facc7 to your computer and use it in GitHub Desktop.
package main
import (
"bufio"
"fmt"
"io"
"log"
"strings"
"unicode"
)
var text = `
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.
`
func main() {
var chars, runes, words, lines int
var inWord bool
buf := bufio.NewReader(strings.NewReader(text))
for {
r, sz, err := buf.ReadRune()
if err != nil {
if err == io.EOF {
if inWord {
words++
inWord = false
}
break
} else {
log.Fatal(err)
}
}
runes++
chars += sz
if unicode.IsSpace(r) {
if r == '\n' {
lines++
}
if inWord {
words++
inWord = false
}
} else if unicode.IsPunct(r) || unicode.IsControl(r) {
if inWord {
words++
inWord = false
}
} else {
inWord = true
}
}
fmt.Printf("%8d %7d %7d %7d\n", lines, words, chars, runes)
}
@caelifer
Copy link
Author

Running version is here - http://play.golang.org/p/tL3NFziKft

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment