Start learning free

LESSON 604 OF 667 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: wc v2 — Count Words

Practice

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:

int countWords(vector<string> lines)

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.


Use an istringstream for each line and pull tokens with >>. The stream operator skips whitespace automatically and stops at end-of-string.

istringstream ss(lines[i]);
string word;
while (ss >> word) {
    total++;
}


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

STEP 1 OF 7
    Ctrl + Enter to check