Start learning free

LESSON 372 OF 404 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: wc v2 — Count Words in Go

Practice

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

    Wc V2 in Go

    Keep going with GoAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free