Start learning free

LESSON 10 OF 70 · PROJECTS: COMMAND-LINE TOOLS

wc v2 in Scala: Counting Words with trim and split

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:

def 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, and only when it has content, split it on whitespace with "\s+" and add the length:
val trimmed = line.trim
if (trimmed.nonEmpty) {
    total += trimmed.split("\\s+").length
}


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

STEP 1 OF 6
    Ctrl + Enter to check

    SCALA · PROJECTS: COMMAND-LINE TOOLS

    Wc V2 in Scala, explained

    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+").length is 1, not 0. Counting that piece would give an empty line one word.
    • Leading whitespace produces an empty first piece: " a b ".split("\\s+").toList is List("", "a", "b"). Trailing whitespace doesn't produce an extra piece, because split drops 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

    1. Create the total. A var named total, starting at 0, because it changes as lines are counted.
    2. Loop over the lines. for (line <- lines) gives each string of the list in turn.
    3. Trim the line into a val named trimmed. The trimmed copy never changes, so val fits.
    4. Skip blank lines. An if on trimmed.nonEmpty keeps the one-empty-piece result of splitting "" out of the count.
    5. Add the word count. Split trimmed on "\\s+" and add the length of the resulting array to total.
    6. 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.
    • split comes from Java's String and returns an Array[String]; .length is the number of pieces.
    • line.trim is called without parentheses, which Scala allows for a method with no arguments. nonEmpty is the opposite of isEmpty.
    • total += ... works because total is a var. Writing val total = 0 would make this line a compile error.
    • The method's last expression would be its value, so the return could be dropped, but the explicit return total is correct and clear.

    Edge cases and common mistakes

    • Forgetting the nonEmpty check. 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(" ").length is 3 because of the empty piece between the two spaces, while "a b".split("\\s+").length is 2. Splitting on "\\s+" also handles tabs.
    • Using val for the total. It can't be reassigned.

    Testing

    These inputs and their results are worth trying in the editor above:

    InputResult
    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.

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