Project 8: Word Counter
Complete video course: Udemy
Introduction
A word counter is an application that determines the number of words in a string of text the user provides. This could be a single sentence, a paragraph, or even longer.
The user is prompted for some input (text of any length), and the program determines the number of words and finally displays that result back to the user.
Practical
Boilerplate code:
package main
import (
)
func main() {
}
First, we will need to declare a variable (of type string) to store the user-provided text:
var text string
Next, we prompt the user for the text and read it into the variable declared above. Until now, we have only worked with the Scanln function of the fmt package. However, that will not work in this case because the Scanln function and other scanning functions in the fmt package usually read input until they encounter a space or newline character. The downside of this is that only the first word of the user’s input will be read even if they provide text containing multiple words. To avoid that, we will use a different method, involving a different package and functions altogether.
The bufio package (short for buffered input/output) allows us to perform buffered input/output operations, meaning we can easily work with large inputs and outputs. To use it, we will create a new Reader object which takes in as its argument an object of type io.Reader eg. a file handle, os.Stdin (standard input), etc. Since we are reading input from the user, we will pass os.Stdin to it, and then move on to call the ReadString function of this reader with a delimiter of a newline character (meaning we read user input till they hit enter):
import (
"bufio"
"fmt"
"os"
)
reader := bufio.NewReader(os.Stdin)
fmt.Println("Enter a sentence or paragraph:")
text, _ := reader.ReadString('\n')
In the last line of the above snippet, we can see that the ReadString function returns 2 values: the read input, and an error if any. I have used a blank identifier for the error result since I am not interested in using it. Feel free to do error checking if you want (remember how we do it?).
Having read the user input, it is time to determine the number of words. For this, we will use the Fields function of the strings package. This function returns a collection containing all words in the string passed to it, with which we can use len function (short for length) to determine the number of words:
import (
"bufio"
"fmt"
"os"
"strings" // add this to the imports section
)
words := strings.Fields(text)
count := len(words)
Finally, we can display this result back to the user:
fmt.Printf("The number of words is: %d\n", count)
Complete code:
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
var text string
reader := bufio.NewReader(os.Stdin)
fmt.Println("Enter a sentence or paragraph:")
text, _ = reader.ReadString('\n')
words := strings.Fields(text)
count := len(words)
fmt.Printf("The number of words is: %d\n", count)
}