Problem overview
This version of the wc project builds the -w behaviour: countWords takes a List[String] of lines and returns the total number of words, as an Int. A word is a run of non-whitespace characters, and words are separated by one or more spaces or tabs. The input is plain ASCII.
For ["hello world", "foo bar baz", ""] the lines contribute 2, 3 and 0 words, so the answer is 5. A line that is empty or holds only whitespace contributes 0, and an empty list gives 0. Spaces at the start or end of a line don't create words.
Approach
The plan is to visit every line, work out how many words it has, and add that to a running total. The only subtle part is counting the words of one line, because split doesn't behave the way you might expect on blank text.
Splitting on the regular expression "\\s+" cuts a string at every run of whitespace, so two spaces or a tab between words are no problem. Two edge cases matter, and both come from the pieces that split returns:
- Splitting an empty string gives an array with one empty piece, so
"".split("\\s+").lengthis 1, not 0. Counting that piece would give an empty line one word. - Leading whitespace produces an empty first piece:
" a b ".split("\\s+").toListisList("", "a", "b"). Trailing whitespace doesn't produce an extra piece, becausesplitdrops empty pieces at the end.
Trimming the line first fixes both. After trim, a line has no whitespace at either end, so the only way to be empty is to have had no words. Check for that case and skip it; otherwise every piece of the split is a real word.
Step by step
- Create the total. A
varnamedtotal, starting at 0, because it changes as lines are counted. - Loop over the lines.
for (line <- lines)gives each string of the list in turn. - Trim the line into a
valnamedtrimmed. The trimmed copy never changes, sovalfits. - Skip blank lines. An
ifontrimmed.nonEmptykeeps the one-empty-piece result of splitting "" out of the count. - Add the word count. Split
trimmedon"\\s+"and add the length of the resulting array tototal. - Return the total after the loop, once every line has been counted.
The solution in Scala
class Solution {
def countWords(lines: List[String]): Int = {
var total = 0
for (line <- lines) {
val trimmed = line.trim
if (trimmed.nonEmpty) {
total += trimmed.split("\\s+").length
}
}
return total
}
}
A few Scala details are worth knowing:
- In a Scala string literal the backslash is an escape character, so the regex
\s+is written"\\s+". The regex itself sees\s+: one or more whitespace characters, which includes spaces and tabs. splitcomes from Java'sStringand returns anArray[String];.lengthis the number of pieces.line.trimis called without parentheses, which Scala allows for a method with no arguments.nonEmptyis the opposite ofisEmpty.total += ...works becausetotalis avar. Writingval total = 0would make this line a compile error.- The method's last expression would be its value, so the
returncould be dropped, but the explicitreturn totalis correct and clear.
Edge cases and common mistakes
- Forgetting the
nonEmptycheck. An empty line would add 1 instead of 0, and a whitespace-only line would too once trimmed. - Forgetting
trim. A line with leading spaces would count one extra empty piece. - Splitting on a single space.
"a b".split(" ").lengthis 3 because of the empty piece between the two spaces, while"a b".split("\\s+").lengthis 2. Splitting on"\\s+"also handles tabs. - Using
valfor the total. It can't be reassigned.
Testing
These inputs and their results are worth trying in the editor above:
| Input | Result |
|---|---|
List("hello world", "foo bar baz", "") | 5 |
List(" padded words\there ", " ", "one") | 4 |
Nil (an empty list) | 0 |
The second row has leading, trailing and doubled spaces, a tab between words, and a whitespace-only line, so it exercises every case above.
