Start learning free

LESSON 10 OF 69 · PROJECTS: COMMAND-LINE TOOLS

wc -w in C#: Counting Words with Split

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:

public int CountWords(List<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.


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 with StringSplitOptions.RemoveEmptyEntries so consecutive spaces collapse and empty lines yield no tokens, then count:
total += line.Split((char[])null, StringSplitOptions.RemoveEmptyEntries).Length;


The full solution:
class Solution {
    public int CountWords(List<string> lines) {
        int total = 0;
        foreach (string line in lines) {
            total += line.Split((char[])null, StringSplitOptions.RemoveEmptyEntries).Length;
        }
        return total;
    }
}

STEP 1 OF 4
    Ctrl + Enter to check

    C# · PROJECTS: COMMAND-LINE TOOLS

    Wc V2 in C#, explained

    Problem overview

    CountWords takes a List<string> of lines and returns the total number of words in all of them, like wc -w does for a file. A word is a run of characters between spaces or tabs.

    For ["hello world", "foo bar baz", ""] the lines hold 2, 3 and 0 words, so the method returns 5. Extra spaces at either end of a line, or several spaces in a row, never create words. A line that is empty or only whitespace counts 0, and an empty list gives 0.

    Approach

    Counting words means counting the pieces left after cutting each line at its whitespace. You could walk through the characters and track whether you are inside a word, but C# can do the cutting for you: Split returns an array of the pieces, and the array's Length is the count. Do this for every line and add the numbers up.

    The only subtlety is what Split does with gaps. Splitting " a b " on a single space gives 6 pieces, most of them empty strings. Splitting it with StringSplitOptions.RemoveEmptyEntries gives 2, which is the right word count. Splitting an empty string with the option gives 0 pieces, so blank lines need no special case.

    Step by step

    1. Create total. An int that starts at 0 and collects the words of every line.
    2. Loop with foreach. It gives you each string line of the list directly, with no index to manage.
    3. Add the line's word count. Split the line and add the Length of the resulting array to total.
    4. Return total after the loop, once, when every line has been counted.

    The solution in C#

    class Solution {
        public int CountWords(List<string> lines) {
            int total = 0;
            foreach (string line in lines) {
                total += line.Split((char[])null, StringSplitOptions.RemoveEmptyEntries).Length;
            }
            return total;
        }
    }
    

    The details worth knowing:

    • (char[])null means "any whitespace". When the separator array is null, Split cuts at every whitespace character, so tabs and spaces both work. The cast is needed because Split has several overloads, and a bare null would not say which one you mean.
    • RemoveEmptyEntries does the cleanup. Without it, "a b".Split(' ') has three pieces, because of the empty one between the two spaces. With it, you get two. For "a\tb c" the result has 3 words.
    • The result is an array. Arrays have a Length property, while the List of lines has Count. Mixing the two up is a compile error.
    • += adds to the variable. The loop adds a different number for each line, so total ends as the sum.

    Edge cases and common mistakes

    • Empty and blank lines. "" and " " both split into 0 pieces, so they add nothing.
    • Leading and trailing whitespace. " hello " is one word. Splitting on a single space without the option would report 5 pieces.
    • Counting spaces instead of words. The number of spaces plus one is wrong as soon as there are two spaces in a row or a space at an edge.
    • Returning inside the loop. A return there would stop after the first line.
    • An empty list. The loop never runs, and total stays 0.

    Testing

    • ["hello world", "foo bar baz", ""] gives 5.
    • [" a \t\t b ", " "] gives 2.
    • [] 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