Start learning free

LESSON 12 OF 69 · PROJECTS: COMMAND-LINE TOOLS

wc Mode Flag in C#: Lines, Words, Characters

Practice Read the full explanation

Combine the previous three versions of wc. Given a list of lines and a mode flag, return the requested count(s) as a string. This is our own simplified interface, not the real wc flags: the real tool combines flags (such as -lw) and pads its columns with spaces.

Function signature:

public string Wc(List<string> lines, string mode)

Mode values:

  • "l" → line count, as a string.
  • "w" → word count (whitespace-separated tokens), as a string.
  • "c" → character count (lines only, no separating newlines), as a string.
  • "all" → lines + "\t" + words + "\t" + chars.

The "c" count is the one from v3 (the sum of the line lengths, no newlines). Any other mode value, for example "x" or "L" (modes are case-sensitive), gives the same result as "all". For an empty list, "l", "w" and "c" give "0" and "all" gives "0<TAB>0<TAB>0". The input is plain ASCII text.

Example:

Input: lines = ["hello", "world"], mode = "all"

Output: "2\t2\t10"

2 lines, 2 words (one per line), 10 characters total.


Compute all three counts in a single pass through lines, then branch on mode to pick the return value.

int numLines = lines.Count;
int numWords = 0;
int numChars = 0;
foreach (string line in lines) {
    string trimmed = line.Trim();
    if (trimmed.Length > 0) { numWords += trimmed.Split((char[])null, StringSplitOptions.RemoveEmptyEntries).Length; }
    numChars += line.Length;
}
Use .ToString() to convert numbers to strings.

The full solution:
class Solution {
    public string Wc(List<string> lines, string mode) {
        int numLines = lines.Count;
        int numWords = 0;
        int numChars = 0;
        foreach (string line in lines) {
            string trimmed = line.Trim();
            if (trimmed.Length > 0) { numWords += trimmed.Split((char[])null, StringSplitOptions.RemoveEmptyEntries).Length; }
            numChars += line.Length;
        }
        if (mode == "l") { return numLines.ToString(); }
        if (mode == "w") { return numWords.ToString(); }
        if (mode == "c") { return numChars.ToString(); }
        return numLines + "\t" + numWords + "\t" + numChars;
    }
}

STEP 1 OF 11
    Ctrl + Enter to check

    C# · PROJECTS: COMMAND-LINE TOOLS

    Wc V4 in C#, explained

    Problem overview

    Wc combines the three earlier counts. It takes a list of lines and a mode string and returns a string:

    • "l": the number of lines.
    • "w": the number of whitespace-separated words.
    • "c": the total of the line lengths, with no newlines.
    • anything else, "all" included: lines, words and characters joined by tab characters.

    For ["hello", "world"] and mode "all" the result is "2\t2\t10". Modes are case-sensitive, so "L" falls into the "anything else" case. For an empty list, "l", "w" and "c" return "0" and "all" returns "0\t0\t0".

    Approach

    Compute all three numbers once, then pick what to return. The line count needs no loop: it is the size of the list. The word and character counts both grow as the loop reads lines, so one pass collects both. After the loop, a few early returns handle the three single-count modes, and the last line, reached by every other mode, builds the combined string.

    The counts are numbers but the method returns text, so each one must be converted to a string before it is returned.

    The combined output is deliberately simple. The real wc pads its columns with spaces and lets you combine flags, but here the three numbers are joined by single tab characters, so a test can compare the whole string exactly. Check the order when you write the last line: lines first, then words, then characters, the same order as the mode names in the list above.

    A worked example

    Take ["a b", " "] with mode "L". numLines is 2. The first line trims to "a b", which has 2 words, and adds 3 characters. The second line trims to the empty string, so no words are added, but its 2 spaces still count as characters. The totals are 2 lines, 2 words and 5 characters. No mode check matches "L", so the combined string "2\t2\t5" is returned.

    Step by step

    1. Store numLines as the list's Count.
    2. Create numWords and numChars, both ints starting at 0.
    3. Loop over the lines with foreach.
    4. Trim the line into trimmed with Trim(), which removes whitespace at both ends.
    5. Count words only for a non-blank line. If trimmed.Length is above 0, add the number of pieces from splitting it on whitespace, with empty pieces removed.
    6. Add the full line's Length to numChars. This uses line, not trimmed, because the spaces at the edges are characters too.
    7. Return early for "l", "w" and "c", converting the matching number with ToString().
    8. Return the combined string last, for every mode that did not return above.

    The solution in C#

    class Solution {
        public string Wc(List<string> lines, string mode) {
            int numLines = lines.Count;
            int numWords = 0;
            int numChars = 0;
            foreach (string line in lines) {
                string trimmed = line.Trim();
                if (trimmed.Length > 0) { numWords += trimmed.Split((char[])null, StringSplitOptions.RemoveEmptyEntries).Length; }
                numChars += line.Length;
            }
            if (mode == "l") { return numLines.ToString(); }
            if (mode == "w") { return numWords.ToString(); }
            if (mode == "c") { return numChars.ToString(); }
            return numLines + "\t" + numWords + "\t" + numChars;
        }
    }
    

    The details worth knowing:

    • == on strings compares contents. mode == "l" is true for any string with the text l, not only the same object. It is case-sensitive, so "L" does not match.
    • Splitting on null separators cuts at any whitespace, and RemoveEmptyEntries drops the empty pieces. The Trim check keeps blank lines from being split at all, though they would give 0 pieces anyway.
    • + turns numbers into text. In the last line, an int added to a string is converted and appended, so the whole expression is one string. The tab is the escape "\t", a single character.
    • Early returns replace else. Once a branch returns, the code after it only runs for the other modes, so no else is needed.
    • The default is "all". A mode such as "x" skips the three checks and gets the combined string.

    Why one pass

    You could write three small methods, one for each count, and call the right one for the mode. That works, but it reads the lines again for each count, and the combined mode would run all three. Computing the three numbers together in one loop keeps the method short and reads the input once. The cost is that the single-count modes also compute numbers they do not return, which is cheap here.

    Complexity

    Time: O(total characters), since trimming and splitting each line reads it. Space: the split of one line creates an array of its words, so extra memory is proportional to the longest line.

    Edge cases and common mistakes

    • Measuring characters on the trimmed line. That loses the edge spaces. " a " has 4 characters and 1 word.
    • Returning a number. return numLines; does not compile in a method that returns string.
    • Treating "L" or "x" as an error. They get the combined result.
    • An empty list. numLines is 0 and the loop does nothing, so every count is 0.

    Testing

    • ["hello", "world"] with "all" gives "2\t2\t10".
    • ["a b", " "] with "L" gives "2\t2\t5".
    • ["a\tb"] with "c" gives "3".
    • [] with "all" gives "0\t0\t0".
    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