Word Count Program in Go
This document provides a Go program to count the number of words in a given text, along with an explanation of its structure and documentation.
Go Program to Count Words
// WordCount program counts the number of words in a given text.
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
// countWords function takes a string input and returns the word count.
func countWords(text string) int {
// Split the text by spaces and store the words in a slice.
words := strings.Fields(text)
// Return the length of the words slice which is the word count.
return len(words)
}
func main() {
// Create a new reader to read input from standard input (console).
reader := bufio.NewReader(os.Stdin)
fmt.Println("Enter text to count the words:")
// Read the input text from the user.
inputText, _ := reader.ReadString('\n')
// Trim any leading and trailing whitespace from the input text.
inputText = strings.TrimSpace(inputText)
// Call the countWords function and print the word count.
wordCount := countWords(inputText)
fmt.Printf("The number of words in the given text is: %d\n", wordCount)
}
Program Structure and Explanation
The program is structured into several parts, each with a specific role:
- Package Declaration:The
package main
declaration specifies that this is a standalone executable program. - Imports:The
import
statement is used to import necessary packages. In this program, we import:bufio
for buffered I/O operationsfmt
for formatted I/O operationsos
for OS-related functionality (e.g., reading from the console)strings
for string manipulation functions
- countWords Function:This function takes a string as input, splits it into words using
strings.Fields
, and returns the count of words. Thestrings.Fields
function splits the input text by whitespace and returns a slice of words. - main Function:This is the entry point of the program. It performs the following steps:
- Creates a new reader to read input from the standard input (console) using
bufio.NewReader
. - Prompts the user to enter text to count the words.
- Reads the input text from the user until a newline character is encountered using
reader.ReadString('\n')
. - Trims any leading and trailing whitespace from the input text using
strings.TrimSpace
. - Calls the
countWords
function to count the number of words in the input text. - Prints the word count to the console using
fmt.Printf
.
- Creates a new reader to read input from the standard input (console) using
Conclusion
This Go program demonstrates how to count the number of words in a given text input by the user. It showcases basic string manipulation and input/output operations in Go.