Start learning free

LESSON 11 OF 69 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool wc v3 in C++: Count Characters with size()

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:

int countChars(vector<string> lines)

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 lines[i].size() into an int running total.

The full solution:
class Solution {
public:
    int countChars(vector<string> lines) {
        int total = 0;
        for (int i = 0; i < lines.size(); i++) {
            total += lines[i].size();
        }
        return total;
    }
};

STEP 1 OF 4
    Ctrl + Enter to check

    C++ · PROJECTS: COMMAND-LINE TOOLS

    Wc V3 in C++, explained

    Problem overview

    This version of wc counts characters. The function countChars takes a vector<string> of lines and returns the total number of characters as an int. Only the characters inside the lines count. The newline characters that would separate the lines in a file are not counted, and spaces and tabs inside a line count as one character each. The input is plain ASCII text.

    For ["hello", "world"] the answer is 10, because each word has 5 characters. An empty line adds 0, and an empty vector gives 0. The real wc counts differently, since it also counts newlines and has separate modes for bytes and characters, but here the answer is simply the sum of the line lengths.

    Approach: add up the sizes

    This is the same running-total pattern as the word count from the previous version, but easier, because nothing has to be split. A string already knows its length, and size() returns it in constant time. So the answer is the sum of lines[i].size() over all positions.

    Step by step

    1. Create total as an int set to 0. A running total starts at zero, before any line is counted.
    2. Loop over the lines by position with i from 0 while i < lines.size().
    3. Add lines[i].size() to total. This is the only line of work in the loop: each line contributes its own length, spaces and tabs included.
    4. Return total after the loop. The return runs once, when every line has been added.

    The solution in C++

    class Solution {
    public:
        int countChars(vector<string> lines) {
            int total = 0;
            for (int i = 0; i < lines.size(); i++) {
                total += lines[i].size();
            }
            return total;
        }
    };
    

    The C++ details worth a closer look:

    • size() counts char values, which are bytes. For ASCII text that is the same as the number of characters. A letter outside ASCII, such as an accented one, usually takes several bytes in UTF-8, so size() would count more than one for it. That is why the lesson restricts the input to ASCII.
    • size() is unsigned. It returns size_t. The line total += lines[i].size() mixes it with an int and the result is converted back to int when stored. That is harmless for any realistic amount of text, and the lesson's tests stay far below the limits of an int.
    • size() and length() are the same. Both return the number of characters in a string; size() matches the name used by vector and the other containers.
    • Escape sequences are one character. In a C++ string literal, "\t" is a single tab character, so "\tx" has size 2.

    Complexity

    Time: O(n), where n is the number of lines. Each iteration calls size(), which does not look at the characters. The by-value parameter makes the call copy the whole vector, which costs time proportional to the total length, but the counting itself does not.

    Space: O(1) extra besides that copy: one integer for the total and one for the loop counter.

    Edge cases and common mistakes

    • Empty vector. The loop doesn't run and the function returns 0.
    • Empty lines. ["", ""] gives 0, because each empty line has size 0.
    • Whitespace counts. ["a b", "\tx"] gives 5: three characters in the first line (the space is one) and two in the second (the tab is one).
    • Counting newlines. Adding 1 per line for a separator gives a different number than the lesson wants. The answer is the sum of the line lengths and nothing else.
    • Counting words instead. Reusing the stream-based loop from the previous version counts words, not characters.
    • Resetting the total in the loop. Declaring total inside the loop would reset it on every line, and the declaration would not be visible at the return.

    Testing

    • ["hello", "world"] gives 10.
    • ["a b", "\tx"] gives 5.
    • ["", ""] gives 0.
    • [] gives 0.
    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free