Problem overview
This version of the wc project counts words. The function countWords receives a List<String>, one string per line of text, and returns the total number of words in all the lines as an Int. A word is a run of characters without whitespace, and words are separated by one or more spaces or tabs. The input is plain ASCII.
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 with only whitespace counts as 0 too, and an empty list of lines gives 0.
Approach: trim, skip blanks, split
The plan is a running total and a loop over the lines. For each line, you split it into words and add the number of pieces to the total. The only difficulty is what split does at the edges of a string and on an empty one, so the lesson handles those two cases before splitting.
A Kotlin string is cut into pieces with split. Because words can be separated by several spaces or by tabs, the separator is a regular expression, Regex("\\s+"): \s matches one whitespace character and + means "one or more of them". The backslash is written twice because a single backslash starts an escape sequence inside a Kotlin string literal.
Here is what happens when you skip the preparation. These results come from a real run:
println(" a b ".split(Regex("\\s+")))
println("".split(Regex("\\s+")))
println(" ".split(Regex("\\s+")).size)
[, a, b, ]
[]
2
Whitespace at either end produces an empty piece, so " a b " splits into four pieces instead of two. The empty string splits into a list holding one empty string (printed as [] above), and a line made only of a space gives two empty pieces. All of these would be counted as words. Trimming removes the edge whitespace, and checking for an empty result removes the blank lines.
Step by step
- Create the total. A
varnamedtotalstarts at 0, before any line is read. It must be avarbecause it changes with every line. - Loop over the lines. A
forloop gives each string oflinesthe nameline. Close the brace at once so the later steps go inside it. - Trim the line.
line.trim()returns a copy without whitespace at either end. It is stored in avalnamedtrimmed, since it is never reassigned. - Skip blank lines. If
trimmedis empty,continuejumps to the next line, so the line adds nothing. A whitespace-only line becomes empty after the trim, so one check covers both kinds of blank line. - Add the words. Split
trimmedat every run of whitespace and add thesizeof the resulting list tototal. After the trim and the skip, every piece is a real word. - Return the total after the loop, once every line has been counted.
The solution in Kotlin
class Solution {
fun countWords(lines: List<String>): Int {
var total = 0
for (line in lines) {
val trimmed = line.trim()
if (trimmed.isEmpty()) { continue }
total += trimmed.split(Regex("\\s+")).size
}
return total
}
}
A few Kotlin details are worth knowing:
continueends the current pass of the loop and starts the next one, so the line with thesplitnever runs for a blank line.total += xis shorthand fortotal = total + x. It only compiles becausetotalis avar.trim()doesn't change the original string. Strings in Kotlin are immutable, and the call returns a new one.split(Regex(...))returns aList<String>, which is whysize(notlength) gives the count.
Edge cases and common mistakes
- Splitting on a single space.
split(" ")treats each space as a separator, so two spaces in a row create an empty piece between them, and a tab isn't a separator at all:"a\tb".split(" ")stays as one piece. The regex\s+handles both. - Forgetting the empty-line check. Without it, an empty line adds 1, because splitting
""gives one empty piece. - Forgetting the trim. A line like
" a b "would count 4 instead of 2. - A single backslash in the string.
"\s+"doesn't compile in Kotlin, because\sisn't a valid escape sequence in a string literal. Write"\\s+".
Testing
These inputs and results come from running the reference solution:
| lines | result |
|---|---|
["hello world", "foo bar baz", ""] | 5 |
[" a \t b ", " ", "x"] | 3 |
["a b"] | 2 |
[] | 0 |
Try them in the editor above. The next version of the project builds on this one.
