Problem overview
This version combines the line, word and character counts into one function: wc(lines []string, mode string) string. The mode picks what to report, and the result is always a string, like the text a command-line tool prints.
"l"returns the number of lines,"w"the number of words and"c"the number of characters, each as text."all"returns the three counts in that order, separated by tab characters.- Any other mode behaves like
"all". Modes are case-sensitive, so"L"falls into this group.
For ["hello", "world"] and mode "all", the result is "2\t2\t10": 2 lines, 2 words, 10 characters. Characters are the sum of the line lengths, with no newlines counted, and the input is plain ASCII.
Approach
Compute all three numbers first, then choose which one to return. That is simpler than three separate passes, and it needs only one loop: the line count is just len(lines), while the words and characters are running totals updated for every line. After the loop, a few if checks decide the output. The "all" case is not tested at all: it is the fall-through at the bottom, which also handles every unknown mode.
The lesson's earlier versions each answered one question with its own function. Here the three questions share one pass over the data, and the mode only selects which answer leaves the function. That keeps the code short, and the cost of computing a number nobody asked for is a few additions per line.
Tracing the loop
For ["hello world", "foo bar baz", ""], numLines is 3 from the start. The loop then updates the other two totals:
| Line | Length | Words | numWords after | numChars after |
|---|---|---|---|---|
"hello world" | 11 | 2 | 2 | 11 |
"foo bar baz" | 11 | 3 | 5 | 22 |
"" | 0 | 0 | 5 | 22 |
The totals are 3, 5 and 22, so mode "all" returns "3\t5\t22".
Step by step
- Store the line count.
numLines := len(lines)needs no loop. - Start the word total and the character total at 0, each with
:=. Both grow as lines are read. - Loop over the lines with
for _, line := range lines. - Add the words.
len(strings.Fields(line))counts the whitespace-separated words, as in the word-count version. - Add the characters.
len(line)includes spaces and tabs, as in the character-count version. - Return a single count for
"l","w"and"c". Each returns its number converted to text, oneifper mode. - Return all three as the last statement, formatted with tabs between them. It runs only when none of the earlier modes matched.
The solution in Go
func wc(lines []string, mode string) string {
numLines := len(lines)
numWords := 0
numChars := 0
for _, line := range lines {
numWords += len(strings.Fields(line))
numChars += len(line)
}
if mode == "l" { return strconv.Itoa(numLines) }
if mode == "w" { return strconv.Itoa(numWords) }
if mode == "c" { return strconv.Itoa(numChars) }
return fmt.Sprintf("%d\t%d\t%d", numLines, numWords, numChars)
}
Go details worth knowing:
strconv.Itoaconverts anintto a string. The conversionstring(numLines)would not do this: it treats the number as a character code and gives the character with that code. That is why the function usesstrconv.Itoa.fmt.Sprintfbuilds a string. It works likePrintfbut returns the text instead of printing it. Each%dtakes the next argument as a decimal integer, and\tin the format is a tab character.- One-line
ifblocks. Go requires braces around the body of anif, but they may sit on the same line, as inif mode == "l" { return ... }. There are no parentheses around the condition. - Strings compare with
==. It compares contents, somode == "l"is true exactly when the text isl. - No
elseneeded. Each branch returns, so the code after it only runs when the branch was skipped.
The same choice can be written with a switch, which is common in Go once there are several fixed values to compare. After the loop, it would read:
switch mode {
case "l":
return strconv.Itoa(numLines)
case "w":
return strconv.Itoa(numWords)
case "c":
return strconv.Itoa(numChars)
default:
return fmt.Sprintf("%d\t%d\t%d", numLines, numWords, numChars)
}
Its default case plays the part of the final return above, and a Go switch doesn't fall through from one case to the next, so no break is needed. It gives the same results for "l", "w", "c", "all" and "L". The lesson uses separate if statements, which is what the steps build.
Complexity
Time: O(n), where n is the total number of characters, because the loop scans each line once. The mode check is constant time. Space: O(w), at most the word slice of the longest line, which strings.Fields builds temporarily.
Edge cases and common mistakes
- Empty list.
"l","w"and"c"return"0", and"all"returns"0\t0\t0". - Unknown or differently cased mode.
"x"and"L"give the same result as"all". For["hello", "world"]both return"2\t2\t10". - Empty lines. They count as lines, add no words and no characters. For
["hello world", "foo bar baz", ""], mode"all"returns"3\t5\t22". - Converting with
string(n). It compiles, but it returns a one-character string, not the digits. - Leaving a total unused. Go refuses to compile a variable that is declared and never read. Here all three,
numLines,numWordsandnumChars, are read by the finalreturn, so none of them triggers the error, even though a single-count mode ignores two of them. - Returning a number. The function's result type is
string, so returningnumLinesdirectly is a compile error.
Testing
["hello", "world"]with"l"gives"2", with"w"gives"2", with"c"gives"10".["hello world", "foo bar baz", ""]with"all"gives"3\t5\t22".[]with"all"gives"0\t0\t0".["hello", "world"]with"L"gives"2\t2\t10".
