Last active
September 18, 2015 22:14
-
-
Save caelifer/4e34564adb3e891facc7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Running version is here - http://play.golang.org/p/tL3NFziKft