Introduction
Counting the number of words in a string is a common text-processing task. A word is typically defined as a sequence of characters separated by whitespace. This guide will demonstrate how to write a Go program that counts the number of words in a given string.
Problem Statement
Create a Go program that:
- Prompts the user to enter a string.
- Counts the number of words in the string.
- Displays the word count.
Example:
- Input:
"Hello, World! Welcome to Go." - Output:
Number of words: 5
Solution Steps
- Import the fmt and strings Packages: Use
import "fmt"for formatted I/O operations andimport "strings"for string manipulation functions. - Write the Main Function: Define the
mainfunction, which is the entry point of every Go program. - Input the String: Use
fmt.Scanlnorfmt.Scanfto take input from the user for the string. - Split the String into Words: Use
strings.Fieldsto split the string into individual words. - Count the Words: Use the
lenfunction to count the number of elements in the slice of words. - Display the Word Count: Use
fmt.Printlnto display the number of words.
Go Program
package main
import (
"fmt"
"strings"
)
/**
* Go Program to Count the Number of Words in a String
* Author: https://www.javaguides.net/
*/
func main() {
// Step 1: Declare a variable to hold the input string
var input string
// Step 2: Prompt the user to enter a string
fmt.Print("Enter a string: ")
fmt.Scanln(&input)
// Step 3: Split the string into words
words := strings.Fields(input)
// Step 4: Count the number of words
wordCount := len(words)
// Step 5: Display the word count
fmt.Printf("Number of words: %d\n", wordCount)
}
Explanation
Step 1: Declare Variables
- The variable
inputis declared to store the user’s input string.
Step 2: Input the String
- The program prompts the user to enter a string using
fmt.Print. Thefmt.Scanlnfunction reads the input and stores it in theinputvariable.
Step 3: Split the String into Words
- The
strings.Fieldsfunction is used to split the input string into a slice of words. This function automatically handles multiple spaces and trims any leading or trailing spaces.
Step 4: Count the Number of Words
- The
lenfunction is used to determine the number of elements in thewordsslice, which corresponds to the number of words in the input string.
Step 5: Display the Word Count
- The program prints the word count using
fmt.Printf, which allows for formatted output.
Output Example
Example 1:
Enter a string: Hello, World! Welcome to Go.
Number of words: 5
Example 2:
Enter a string: Go is a statically typed, compiled programming language.
Number of words: 8
Conclusion
This Go program demonstrates how to count the number of words in a string using the strings.Fields function. It covers basic programming concepts such as string manipulation, slices, and input/output operations. This example is useful for beginners learning Go programming and understanding how to process and analyze text.