Start learning free

LESSON 10 OF 71 · PROJECTS: COMMAND-LINE TOOLS

Word Count in Swift: Building wc -w with split(whereSeparator:)

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:

func countWords(_ lines: [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. Splitting on runs of whitespace naturally drops empty pieces, so blank or whitespace-only lines contribute zero.

Split each line on whitespace and count the tokens. split(whereSeparator:) collapses consecutive whitespace and omits empty pieces, so empty lines add nothing:
total += line.split(whereSeparator: { $0.isWhitespace }).count


The full solution:
class Solution {
    func countWords(_ lines: [String]) -> Int {
        var total = 0
        for line in lines {
            total += line.split(whereSeparator: { $0.isWhitespace }).count
        }
        return total
    }
}

STEP 1 OF 4
    Ctrl + Enter to check

    SWIFT · PROJECTS: COMMAND-LINE TOOLS

    Wc V2 in Swift, explained

    Problem overview

    This version of the wc project counts words. The function countWords(_ lines: [String]) -> Int receives an array of lines and returns the total number of words across all of them. A word is a run of characters separated from the next one by spaces or tabs. Leading and trailing whitespace is ignored, a line with no words adds 0, and an empty array gives 0.

    For ["hello world", "foo bar baz", ""] the lines contribute 2, 3 and 0 words, so the answer is 5. The previous version only counted lines, so it never looked inside a string. This one has to.

    Approach

    Counting words is the same as counting the pieces left after cutting a line at every whitespace character and throwing away the empty pieces. Swift has a method for exactly that: split(whereSeparator:). It takes a closure that returns true for each character where the string should be cut, and it gives back an array of the pieces between the cuts.

    By default split omits empty pieces. That is the behaviour this lesson needs. In " a b\tc " there are runs of separators at the start, in the middle and at the end, and every one of them would otherwise create empty pieces. With the default, the pieces are just a, b and c, and a line made only of spaces gives an empty array, so it adds 0 with no special case.

    The closure { $0.isWhitespace } uses the shorthand argument $0, the character being tested, and the isWhitespace property of Character. It is true for a space and a tab, which are the two separators the statement mentions.

    Step by step

    1. Create a running total. A var named total starts at 0, so an empty array of lines returns 0 without any extra code.
    2. Loop over the lines. A for line in lines loop hands over one string at a time. The loop's closing brace goes in right away so the following steps can sit inside it.
    3. Add this line's word count. Split the line where the character is whitespace and read count of the result. That number goes into total with +=.
    4. Return the total after the loop, once every line has been counted. The return is outside the loop, so it runs once.

    The solution in Swift

    class Solution {
        func countWords(_ lines: [String]) -> Int {
            var total = 0
            for line in lines {
                total += line.split(whereSeparator: { $0.isWhitespace }).count
            }
            return total
        }
    }
    

    A few details are worth knowing:

    • The pieces are Substring values. split returns an [Substring], views into the original line rather than new strings. Here only their number matters, so that makes no difference.
    • The closure label. The argument is called whereSeparator, and because the closure is the last argument you could also write it after the parentheses. Keeping it inside, as above, makes the line read as one expression.
    • split(separator: " ") is not the same. That form cuts only at a single character you name. It still omits empty pieces, but it would treat a tab as part of a word. The closure form handles every kind of whitespace at once.

    Complexity

    The function reads each character of each line once, so the time is O(n) where n is the total number of characters in all lines. Extra space is O(w) for the largest number of words in one line, because split builds an array of pieces before count reads its length. Only one line's array exists at a time.

    Edge cases and common mistakes

    • Blank and whitespace-only lines. "", " " and "\t" all give an empty array of pieces, so they add 0.
    • Several separators in a row. "a b" is two words. Counting separators and adding one would get this wrong, and it would also be wrong for an empty line.
    • Keeping empty pieces. Passing omittingEmptySubsequences: false to split keeps them: " x " then gives 4 pieces instead of 1 word. The default is the one this lesson relies on.
    • Counting lines or characters by mistake. lines.count is the number of lines and line.count is the number of characters in one line. The word count is the count of the split result.
    • An empty array. The loop never runs and the function returns the initial 0.

    Testing

    Try these inputs in the editor above:

    InputResult
    ["hello world", "foo bar baz", ""]5
    [" a b\tc ", " ", "\t"]3
    ["one"]1
    []0
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free