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
- Create the total. Declare
totalwith:=and start it at 0. An empty input never enters the loop, so the function then returns 0, which is the right answer. - Loop over the lines.
for _, line := range linesgives each element in turn asline.rangeproduces 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. - Add the line's words. Inside the loop,
strings.Fields(line)returns the words as a slice andlencounts them. Blank lines add 0 without any special case. - 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 := 0makes anint, which matches the function's return type.intis 64 bits on this setup, so overflow isn't a concern for any realistic input.- The result of
Fieldsis only counted. The slice it builds is thrown away afterlen, which is fine at this size. The function needs the number, not the words. - What counts as whitespace.
Fieldssplits 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.
stringsis the package that providesFields.
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
Splitinstead ofFields.["a b"]contains two words, but countingstrings.Split("a b", " ")gives 3, andstrings.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 writingtotal := 0is the way to say it. - Returning inside the loop. A
returnplaced before the closing brace would stop after the first line.
Testing
["hello world", "foo bar baz", ""]gives5.[" a\tb ", " "]gives2.["one", "two three", "\t"]gives3.[]gives0.
