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:

  1. Package Declaration:The package main declaration specifies that this is a standalone executable program.
  2. Imports:The import statement is used to import necessary packages. In this program, we import:
    • bufio for buffered I/O operations
    • fmt for formatted I/O operations
    • os for OS-related functionality (e.g., reading from the console)
    • strings for string manipulation functions
  3. countWords Function:This function takes a string as input, splits it into words using strings.Fields, and returns the count of words. The strings.Fields function splits the input text by whitespace and returns a slice of words.
  4. main Function:This is the entry point of the program. It performs the following steps:
    1. Creates a new reader to read input from the standard input (console) using bufio.NewReader.
    2. Prompts the user to enter text to count the words.
    3. Reads the input text from the user until a newline character is encountered using reader.ReadString('\n').
    4. Trims any leading and trailing whitespace from the input text using strings.TrimSpace.
    5. Calls the countWords function to count the number of words in the input text.
    6. Prints the word count to the console using fmt.Printf.

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.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)