Start learning free

LESSON 10 OF 69 · PROJECTS: COMMAND-LINE TOOLS

wc -w in Go: Counting Words with strings.Fields

Practice Read the full explanation

Build a tiny version of the Unix wc -w command. Given a list of lines, return the total number of words (whitespace-separated tokens) across all lines as an integer.

Function signature:

func countWords(lines []string) int

Example:

Input: lines = ["hello world", "foo bar baz", ""]

Output: 5

The empty string contributes 0 words, "hello world" contributes 2, and "foo bar baz" contributes 3. Total: 5.

Words are separated by one or more spaces or tabs, and leading or trailing whitespace is ignored. A line with no words (empty, or only whitespace) contributes 0, and an empty list of lines gives 0. The input is plain ASCII text.


Iterate over the lines and accumulate the word count. Empty lines must contribute zero.

Use strings.Fields(line): it splits around runs of whitespace and returns an empty slice for an empty or whitespace-only line, so len(strings.Fields(line)) is the word count.

The full solution:
func countWords(lines []string) int {
    total := 0
    for _, line := range lines {
        total += len(strings.Fields(line))
    }
    return total
}

STEP 1 OF 4
    Ctrl + Enter to check

    GO · PROJECTS: COMMAND-LINE TOOLS

    Wc V2 in Go, explained

    Problem overview

    The function countWords takes a slice of strings, lines, and returns the total number of words in all of them, like the Unix wc -w command. A word is a run of characters without whitespace. Words are separated by one or more spaces or tabs, and leading or trailing whitespace is ignored.

    For lines = ["hello world", "foo bar baz", ""] the answer is 5: the first line has 2 words, the second has 3, and the empty line has none. A line made only of whitespace also counts as 0, and an empty slice gives 0.

    Approach

    The problem splits into two smaller ones. Counting the words of a single line is one; adding those counts over all lines is the other. The second is a running total: start at zero, visit each line, add its count.

    The first is where Go's standard library helps. A tempting way is strings.Split(line, " "), but it cuts at every single space. On "a b" (two spaces) it returns three pieces, one of them empty, so counting the pieces gives 3 instead of 2. On an empty string it returns one empty piece, so it reports 1 word where there are none. It also doesn't treat tabs as separators.

    strings.Fields is made for this job. It cuts the string around each run of whitespace, drops the whitespace, and never returns empty pieces. On "a b" it returns two words, and on "" or " " it returns an empty slice. The word count of a line is therefore len(strings.Fields(line)).

    Step by step

    1. Create the total. Declare total with := and start it at 0. An empty input never enters the loop, so the function then returns 0, which is the right answer.
    2. Loop over the lines. for _, line := range lines gives each element in turn as line. range produces an index and a value, and the blank identifier _ discards the index, because Go refuses to compile a variable that is declared and never used.
    3. Add the line's words. Inside the loop, strings.Fields(line) returns the words as a slice and len counts them. Blank lines add 0 without any special case.
    4. Return the total after the loop's closing brace, so it runs once, when every line has been counted.

    The solution in Go

    func countWords(lines []string) int {
        total := 0
        for _, line := range lines {
            total += len(strings.Fields(line))
        }
        return total
    }
    

    Some details of the Go code:

    • := infers the type. total := 0 makes an int, which matches the function's return type. int is 64 bits on this setup, so overflow isn't a concern for any realistic input.
    • The result of Fields is only counted. The slice it builds is thrown away after len, which is fine at this size. The function needs the number, not the words.
    • What counts as whitespace. Fields splits around spaces, tabs, newlines and the other characters Unicode defines as white space. The lesson's input is plain ASCII, so spaces and tabs are all that matter.
    • Imports. strings is the package that provides Fields.

    Complexity

    Time: O(n), where n is the total number of characters. Fields scans each line once, and the loop touches each line once.

    Space: O(w) at most for one line, where w is the number of words in the longest line, because Fields allocates a slice for the words of the current line. Only the total is kept between lines, so the extra space doesn't grow with the number of lines.

    Edge cases and common mistakes

    • Empty slice. Nothing is visited and the function returns 0.
    • Empty or whitespace-only lines. [" a\tb ", " "] gives 2: the first line has two words around its tabs and spaces, and the blank one has none.
    • Using Split instead of Fields. ["a b"] contains two words, but counting strings.Split("a b", " ") gives 3, and strings.Split("", " ") gives a slice of length 1.
    • Forgetting the total's initial value. Go zero-initialises a declared variable, but := needs a value to infer from, so writing total := 0 is the way to say it.
    • Returning inside the loop. A return placed before the closing brace would stop after the first line.

    Testing

    • ["hello world", "foo bar baz", ""] gives 5.
    • [" a\tb ", " "] gives 2.
    • ["one", "two three", "\t"] gives 3.
    • [] gives 0.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free