Start learning free

LESSON 11 OF 70 · PROJECTS: COMMAND-LINE TOOLS

wc v3 in Scala: Counting Characters with length

Practice Read the full explanation

Build a tiny version of the character count of the Unix wc command. Given a list of lines, return the total number of characters across all lines as an integer.

Convention: count only the characters in each line — do not count the implicit newlines that separate them. Spaces and tabs inside a line count as one character each.

Note: this is a simplified version. The real wc -m also counts the newlines, and the real wc -c counts bytes, not characters. Here the answer is simply the sum of the line lengths. The input is plain ASCII text (other alphabets are counted differently by different languages).

Function signature:

def countChars(lines: Array[String]): Int

Example:

Input: lines = ["hello", "world"]

Output: 10

"hello" has 5 chars and "world" has 5 chars, for a total of 10.

An empty line adds 0, and an empty list of lines gives 0.


Loop through the lines and accumulate line.length into an Int running total.

The full solution:
class Solution {
    def countChars(lines: Array[String]): Int = {
        var total = 0
        for (line <- lines) {
            total += line.length
        }
        return total
    }
}

STEP 1 OF 4
    Ctrl + Enter to check

    SCALA · PROJECTS: COMMAND-LINE TOOLS

    Wc V3 in Scala, explained

    Problem overview

    This version counts characters. countChars takes an Array[String] of lines and returns the sum of the line lengths as an Int. The newlines that would separate the lines in a file are not counted, and a space or a tab inside a line counts as one character like any other. The input is plain ASCII.

    For ["hello", "world"] the lines have 5 and 5 characters, so the answer is 10. An empty line adds 0 and an empty array gives 0.

    The real wc counts newlines too (and, with -c, bytes instead of characters). This lesson uses the simpler rule: add up the line lengths.

    Approach

    This is the smallest of the three counters. The previous version had to decide what a word is; here nothing needs deciding, because the number of characters in a line is already the line's length. So the function is a running total over the array: start at zero, add each line's length, return the total.

    Whitespace needs no special handling. For the lines "a b\tc", "" and "xy" the lengths are 5, 0 and 2 (the tab is one character), and the function returns 7. Don't trim the lines: trimming would remove characters that the count is supposed to include.

    Step by step

    1. Create the total. A var named total, starting at 0.
    2. Loop over the lines with for (line <- lines).
    3. Add the length. Each pass adds line.length to total.
    4. Return the total after the loop. If it were inside the loop, the function would stop after the first line.

    The solution in Scala

    class Solution {
        def countChars(lines: Array[String]): Int = {
            var total = 0
            for (line <- lines) {
                total += line.length
            }
            return total
        }
    }
    

    Some details to notice:

    • The parameter is an Array[String]. A Scala Array has a fixed size and can be looped over with for exactly like a List.
    • line.length is a method call written without parentheses. It counts the 16-bit units of the string; for plain ASCII text that is the same as the number of characters, which is why the lesson restricts the input to ASCII.
    • total is an Int, which is 32 bits and wraps silently on overflow. That would take more than two billion characters, far more than this lesson's inputs hold.
    • A var is needed because total is updated with +=; a val would not compile.

    Complexity

    The function visits each line once and reads its length, which takes constant time for a string, so the time is O(n) in the number of lines. It keeps one integer, so the extra space is O(1).

    Edge cases and common mistakes

    • Counting the separators. ["hello", "world"] gives 10, not 11. The newline between the lines is not part of any line.
    • Trimming. Leading and trailing spaces count here. The word counter had to ignore them; this one must not.
    • Returning inside the loop. That returns the length of the first line only.
    • Mixing up lines and characters. lines.length is the number of lines, while line.length is the length of one line.

    Testing

    InputResult
    Array("hello", "world")10
    Array("a b\tc", "", "xy")7
    Array() of strings0
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free