Start learning free

LESSON 610 OF 671 · PROJECTS: COMMAND-LINE TOOLS

wc Mode Flag in Java: Lines, Words, Characters or All

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 with .equals() (NOT ==).

int numLines = lines.size();
int numWords = 0;
int numChars = 0;
for (String line : lines) {
    String trimmed = line.trim();
    if (!trimmed.isEmpty()) numWords += trimmed.split("\\s+").length;
    numChars += line.length();
}


The full solution:
class Solution {
    public String wc(List<String> lines, String mode) {
        int numLines = lines.size();
        int numWords = 0;
        int numChars = 0;
        for (String line : lines) {
            String trimmed = line.trim();
            if (!trimmed.isEmpty()) numWords += trimmed.split("\\s+").length;
            numChars += line.length();
        }
        if (mode.equals("l")) return Integer.toString(numLines);
        if (mode.equals("w")) return Integer.toString(numWords);
        if (mode.equals("c")) return Integer.toString(numChars);
        return numLines + "\t" + numWords + "\t" + numChars;
    }
}

STEP 1 OF 11
    Ctrl + Enter to check

    JAVA · PROJECTS: COMMAND-LINE TOOLS

    Wc V4 in Java, explained

    Problem overview

    The method wc combines the three earlier counters. It takes a List<String> of lines and a String mode, and returns a String:

    • "l" gives the number of lines;
    • "w" gives the number of words, meaning whitespace-separated tokens;
    • "c" gives the number of characters, the sum of the line lengths with no newlines counted;
    • "all" gives the three numbers separated by tab characters: lines, words, characters.

    Any other mode, such as "x" or "L" (modes are case-sensitive), behaves like "all". This interface is the lesson's own, not the real wc flags. For ["hello", "world"] with mode "all" the result is "2\t2\t10": 2 lines, 2 words and 10 characters.

    Approach: count everything once, then choose

    Computing the answer for one mode needs the same loop as for another, so the method counts all three numbers in a single pass and picks the one to return afterwards. The line count needs no loop at all: it is the size of the list. Words and characters are accumulated while the loop reads each line.

    Returning the right thing is an if chain on mode. Each of the three known modes returns early, and the last line, which handles "all" and every unknown mode, is reached only when none of them matched. That is how unknown modes fall back to the full report without any extra code.

    The cost of computing all three numbers even when only one is asked for is small: the loop is linear and the extra work per line is one trim, one split and one length. Writing three separate loops, one per mode, would repeat the same traversal code and make the modes easier to get out of step with each other, for example by trimming in one place and forgetting it in another. One pass with three counters keeps the definitions of a word and a character in a single place.

    Step by step

    1. Store the line count in numLines with lines.size().
    2. Create numWords and numChars as ints starting at 0. They grow as the loop reads lines.
    3. Loop over the lines with a for-each loop, naming each entry line.
    4. Trim the line into trimmed. Spaces at the two ends would produce empty pieces when splitting.
    5. Add the words, if there are any. If trimmed is not empty, add trimmed.split("\\s+").length to numWords. An empty string split this way returns one empty piece, so blank lines must be skipped.
    6. Add the characters. line.length() comes from the original line, not trimmed, because spaces count as characters here.
    7. Return the line count for "l". The method returns text, so Integer.toString(numLines) converts the int. Compare the mode with equals, not ==.
    8. Return the word count for "w" the same way.
    9. Return the character count for "c" the same way.
    10. Return the combined text last, outside any branch, with the three numbers joined by "\t".

    The solution in Java

    class Solution {
        public String wc(List<String> lines, String mode) {
            int numLines = lines.size();
            int numWords = 0;
            int numChars = 0;
            for (String line : lines) {
                String trimmed = line.trim();
                if (!trimmed.isEmpty()) numWords += trimmed.split("\\s+").length;
                numChars += line.length();
            }
            if (mode.equals("l")) return Integer.toString(numLines);
            if (mode.equals("w")) return Integer.toString(numWords);
            if (mode.equals("c")) return Integer.toString(numChars);
            return numLines + "\t" + numWords + "\t" + numChars;
        }
    }
    

    The Java details worth a closer look:

    • equals against ==. On objects, == compares references, not contents. A mode that arrives as a different String object with the same text fails the == test: with String m1 = new String("l"), m1 == "l" is false and m1.equals("l") is true. Calling wc(["a"], m1) returns "1" with equals, as it should.
    • Which side calls equals. mode.equals("l") would throw a NullPointerException if mode were null. The lesson never passes null, but "l".equals(mode) is the habit that tolerates it.
    • Joining numbers and text with +. In numLines + "\t" + numWords + ... the first + has an int on the left and a String on the right, so Java converts the number to text and concatenates. The order matters: 1 + 2 + "\t" adds the numbers first and gives "3\t". Here a string appears right after the first number, so each number becomes text on its own.
    • The tab character. "\t" is a single tab, one character, not a backslash and a letter.

    Complexity

    Time: O(n), where n is the total number of characters: one pass trims, splits and measures each line. The line count is O(1).

    Space: O(m), where m is the longest line, for the trimmed copy and the pieces of one split at a time.

    Edge cases and common mistakes

    • An empty list. "l", "w" and "c" each return "0", and "all" returns "0\t0\t0".
    • Unknown modes. "x" and "L" return the same text as "all", "2\t2\t10" for the hello and world example.
    • Blank lines in the middle. ["one two", "", " three "] with "all" gives "3\t3\t16". The empty line counts as a line, adds no words and no characters, and the padding spaces around three are part of the character count.
    • Counting characters from trimmed. That drops the surrounding spaces and gives too small a total.
    • Returning a number. The method's return type is String. return numLines; does not compile.
    • A word count without the empty check. A blank line would add 1.

    Testing

    With lines = ["hello", "world"]:

    • mode "l" gives "2";
    • mode "w" gives "2";
    • mode "c" gives "10";
    • mode "all" gives "2\t2\t10".

    Other inputs: [] with "all" gives "0\t0\t0", [] with "w" gives "0", and ["one two", "", " three "] with "all" gives "3\t3\t16".

    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free