0
0
GoProgramBeginner · 2 min read

Go Program to Count Words in String

In Go, you can count words in a string by using strings.Fields(yourString) to split the string into words and then get the length with len(), like wordCount := len(strings.Fields(yourString)).
📋

Examples

InputHello world
Output2
InputGo is fun to learn
Output5
Input
Output0
🧠

How to Think About It

To count words in a string, first split the string into parts separated by spaces or other whitespace. Each part is a word. Then count how many parts you have. This works because words are usually separated by spaces.
📐

Algorithm

1
Get the input string.
2
Split the string into words using whitespace as separator.
3
Count the number of words obtained.
4
Return or print the count.
💻

Code

go
package main

import (
	"fmt"
	"strings"
)

func main() {
	text := "Go is fun to learn"
	words := strings.Fields(text)
	count := len(words)
	fmt.Println(count)
}
Output
5
🔍

Dry Run

Let's trace the string "Go is fun to learn" through the code

1

Input string

text = "Go is fun to learn"

2

Split string into words

words = ["Go", "is", "fun", "to", "learn"]

3

Count words

count = 5

4

Print count

Output: 5

IterationWord
1Go
2is
3fun
4to
5learn
💡

Why This Works

Step 1: Splitting the string

The strings.Fields function splits the input string into a slice of words by whitespace.

Step 2: Counting words

The len() function returns the number of elements in the slice, which equals the number of words.

Step 3: Outputting the result

Printing the count shows how many words the input string contains.

🔄

Alternative Approaches

Manual loop with rune check
go
package main

import (
	"fmt"
	"unicode"
)

func countWords(s string) int {
	inWord := false
	count := 0
	for _, r := range s {
		if unicode.IsSpace(r) {
			inWord = false
		} else if !inWord {
			inWord = true
			count++
		}
	}
	return count
}

func main() {
	text := "Go is fun to learn"
	fmt.Println(countWords(text))
}
This method manually checks each character to count words, useful if you want more control but is more complex.
Using bufio.Scanner
go
package main

import (
	"bufio"
	"fmt"
	"strings"
)

func main() {
	text := "Go is fun to learn"
	scanner := bufio.NewScanner(strings.NewReader(text))
	scanner.Split(bufio.ScanWords)
	count := 0
	for scanner.Scan() {
		count++
	}
	fmt.Println(count)
}
Using bufio.Scanner with ScanWords splits words efficiently, good for large input streams.

Complexity: O(n) time, O(n) space

Time Complexity

The program scans each character once to split words, so time grows linearly with input size.

Space Complexity

Splitting creates a slice holding all words, so space also grows linearly with input size.

Which Approach is Fastest?

Using strings.Fields is simple and fast for most cases; manual rune checking is slower but more flexible; bufio.Scanner is efficient for streaming large text.

ApproachTimeSpaceBest For
strings.FieldsO(n)O(n)Simple and small to medium strings
Manual rune checkO(n)O(1)Custom word definitions or low memory
bufio.ScannerO(n)O(n)Large input streams or files
💡
Use strings.Fields for a quick and simple word count in Go.
⚠️
Beginners often forget to import strings package or use len() on the original string instead of the split words.