Start learning free

LESSON 11 OF 71 · PROJECTS: COMMAND-LINE TOOLS

Character Count in Swift: Building wc with String.count

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:

func countChars(_ lines: [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.count into an Int running total.

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

STEP 1 OF 4
    Ctrl + Enter to check

    SWIFT · PROJECTS: COMMAND-LINE TOOLS

    Wc V3 in Swift, explained

    Problem overview

    The third version of the wc project counts characters. The function countChars(_ lines: [String]) -> Int receives an array of lines and returns the sum of their lengths. Spaces and tabs inside a line count as one character each. The newlines that would separate the lines in a real file are not counted, and the input is plain ASCII text.

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

    This is a simplified version of the real tool. The real wc -m also counts the newlines, and wc -c counts bytes. Here the answer is simply the sum of the line lengths.

    Approach

    The task has the same shape as the word count: go through the lines, measure each one, and add the measurements to a total. Only the measurement changes. A String in Swift has a count property that gives its number of characters, so the work for one line is a single property read.

    There is no separator logic here, because every character counts, whitespace included. That also means the function needs no special case for blank lines: "".count is 0 and adds nothing.

    Step by step

    1. Create a running total. A var named total starts at 0, which is also the right answer for an empty array.
    2. Loop over the lines. A for line in lines loop gives one string per pass. Its closing brace goes in first so the next step has a place to live.
    3. Add the line's length. line.count is the number of characters in that line, and += adds it to total.
    4. Return the total after the loop, so it runs once with every line already counted.

    The solution in Swift

        func countChars(_ lines: [String]) -> Int {
            var total = 0
            for line in lines {
                total += line.count
            }
            return total
        }
    

    The function is a method of the lesson's Solution class, and the underscore in _ lines lets callers pass the array without a label.

    What count counts

    For a String, count counts Character values, which are what a reader would call characters. In Swift one Character can be made of several Unicode scalars. The word "café" written with the single scalar for the accented letter and the same word written as e plus a combining accent both have count 4. Their utf8.count values, the number of bytes, are 5 and 6. Even "\r\n", a carriage return followed by a line feed, is a single Character with count 1.

    Because the lesson's input is plain ASCII, characters and bytes agree: "hello".count and "hello".utf8.count are both 5. The difference only shows up with other alphabets, which is why the statement keeps the input to ASCII and why a byte count, like the real wc -c, would be a different function.

    Strings are not arrays

    Both lines.count and line.count exist, and they answer different questions. lines.count is the number of lines. line.count is the number of characters in one line. Reading an array's count is constant time, but a String has to walk its contents to find character boundaries, so line.count takes time proportional to the line's length.

    Complexity

    Time is O(n), where n is the total number of characters in all lines: each line's count walks that line once. Extra space is O(1), a single integer.

    Edge cases and common mistakes

    • Don't count the newlines. Joining the lines with "\n" and counting the result gives 11 for ["hello", "world"], because of the separator. The lesson wants 10.
    • Spaces and tabs count. "a b\tc" has 5 characters. Trimming or splitting the line first would lose some of them.
    • Empty lines and empty arrays. Both add 0.
    • Using the wrong count. Returning lines.count gives the number of lines, which was the first version's job.
    • Indexing a string with an integer. Swift doesn't allow line[0] on a String. You don't need it here, since count already gives the length.

    Testing

    Try these inputs in the editor above:

    InputResult
    ["hello", "world"]10
    ["a b\tc", ""]5
    ["", ""]0
    []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