Problem overview
This version of the wc project counts words. The function countWords(_ lines: [String]) -> Int receives an array of lines and returns the total number of words across all of them. A word is a run of characters separated from the next one by spaces or tabs. Leading and trailing whitespace is ignored, a line with no words adds 0, and an empty array gives 0.
For ["hello world", "foo bar baz", ""] the lines contribute 2, 3 and 0 words, so the answer is 5. The previous version only counted lines, so it never looked inside a string. This one has to.
Approach
Counting words is the same as counting the pieces left after cutting a line at every whitespace character and throwing away the empty pieces. Swift has a method for exactly that: split(whereSeparator:). It takes a closure that returns true for each character where the string should be cut, and it gives back an array of the pieces between the cuts.
By default split omits empty pieces. That is the behaviour this lesson needs. In " a b\tc " there are runs of separators at the start, in the middle and at the end, and every one of them would otherwise create empty pieces. With the default, the pieces are just a, b and c, and a line made only of spaces gives an empty array, so it adds 0 with no special case.
The closure { $0.isWhitespace } uses the shorthand argument $0, the character being tested, and the isWhitespace property of Character. It is true for a space and a tab, which are the two separators the statement mentions.
Step by step
- Create a running total. A
varnamedtotalstarts at 0, so an empty array of lines returns 0 without any extra code. - Loop over the lines. A
for line in linesloop hands over one string at a time. The loop's closing brace goes in right away so the following steps can sit inside it. - Add this line's word count. Split the line where the character is whitespace and read
countof the result. That number goes intototalwith+=. - Return the total after the loop, once every line has been counted. The
returnis outside the loop, so it runs once.
The solution in Swift
class Solution {
func countWords(_ lines: [String]) -> Int {
var total = 0
for line in lines {
total += line.split(whereSeparator: { $0.isWhitespace }).count
}
return total
}
}
A few details are worth knowing:
- The pieces are
Substringvalues.splitreturns an[Substring], views into the original line rather than new strings. Here only their number matters, so that makes no difference. - The closure label. The argument is called
whereSeparator, and because the closure is the last argument you could also write it after the parentheses. Keeping it inside, as above, makes the line read as one expression. split(separator: " ")is not the same. That form cuts only at a single character you name. It still omits empty pieces, but it would treat a tab as part of a word. The closure form handles every kind of whitespace at once.
Complexity
The function reads each character of each line once, so the time is O(n) where n is the total number of characters in all lines. Extra space is O(w) for the largest number of words in one line, because split builds an array of pieces before count reads its length. Only one line's array exists at a time.
Edge cases and common mistakes
- Blank and whitespace-only lines.
""," "and"\t"all give an empty array of pieces, so they add 0. - Several separators in a row.
"a b"is two words. Counting separators and adding one would get this wrong, and it would also be wrong for an empty line. - Keeping empty pieces. Passing
omittingEmptySubsequences: falsetosplitkeeps them:" x "then gives 4 pieces instead of 1 word. The default is the one this lesson relies on. - Counting lines or characters by mistake.
lines.countis the number of lines andline.countis the number of characters in one line. The word count is the count of the split result. - An empty array. The loop never runs and the function returns the initial 0.
Testing
Try these inputs in the editor above:
| Input | Result |
|---|---|
["hello world", "foo bar baz", ""] | 5 |
[" a b\tc ", " ", "\t"] | 3 |
["one"] | 1 |
[] | 0 |
