Start learning free

LESSON 10 OF 70 · PROJECTS: COMMAND-LINE TOOLS

Counting Words in Kotlin: a Tiny wc -w

Practice Read the full explanation

Build a tiny version of the Unix wc -w command. Given a list of lines, return the total number of words (whitespace-separated tokens) across all lines as an integer.

Function signature:

fun countWords(lines: List<String>): Int

Example:

Input: lines = ["hello world", "foo bar baz", ""]

Output: 5

The empty string contributes 0 words, "hello world" contributes 2, and "foo bar baz" contributes 3. Total: 5.

Words are separated by one or more spaces or tabs, and leading or trailing whitespace is ignored. A line with no words (empty, or only whitespace) contributes 0, and an empty list of lines gives 0. The input is plain ASCII text.


Iterate over the lines and accumulate the word count. Trim each line first so that an empty or whitespace-only line contributes zero rather than a stray token.

Trim the line, skip it if it's empty, otherwise split on a whitespace regex and take the size:
val trimmed = line.trim()
if (trimmed.isEmpty()) { continue }
total += trimmed.split(Regex("\\s+")).size


The full solution:
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
    }
}

STEP 1 OF 6
    Ctrl + Enter to check

    KOTLIN · PROJECTS: COMMAND-LINE TOOLS

    Wc V2 in Kotlin, explained

    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

    1. Create the total. A var named total starts at 0, before any line is read. It must be a var because it changes with every line.
    2. Loop over the lines. A for loop gives each string of lines the name line. Close the brace at once so the later steps go inside it.
    3. Trim the line. line.trim() returns a copy without whitespace at either end. It is stored in a val named trimmed, since it is never reassigned.
    4. Skip blank lines. If trimmed is empty, continue jumps 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.
    5. Add the words. Split trimmed at every run of whitespace and add the size of the resulting list to total. After the trim and the skip, every piece is a real word.
    6. 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:

    • continue ends the current pass of the loop and starts the next one, so the line with the split never runs for a blank line.
    • total += x is shorthand for total = total + x. It only compiles because total is a var.
    • trim() doesn't change the original string. Strings in Kotlin are immutable, and the call returns a new one.
    • split(Regex(...)) returns a List<String>, which is why size (not length) 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 \s isn't a valid escape sequence in a string literal. Write "\\s+".

    Testing

    These inputs and results come from running the reference solution:

    linesresult
    ["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.

    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free