Start learning free

LESSON 10 OF 69 · PROJECTS: COMMAND-LINE TOOLS

wc -w in Java: Counting Words in a List of Lines

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. Java's String.split("\\s+") on an empty/whitespace-only line still returns an array of length 1 — so handle the empty case explicitly.

Trim the line, skip it if it's empty, otherwise split:
String trimmed = line.trim();
if (trimmed.isEmpty()) continue;
total += trimmed.split("\\s+").length;


The full solution:
class Solution {
    public int countWords(List<String> lines) {
        int total = 0;
        for (String line : lines) {
            String trimmed = line.trim();
            if (trimmed.isEmpty()) continue;
            total += trimmed.split("\\s+").length;
        }
        return total;
    }
}

STEP 1 OF 6
    Ctrl + Enter to check

    JAVA · PROJECTS: COMMAND-LINE TOOLS

    Wc V2 in Java, explained

    Problem overview

    The method countWords takes a List<String> of lines and returns the total number of words in all of them. This is a small version of the Unix wc -w command. A word is a run of characters separated from the next one by one or more spaces or tabs. Leading and trailing whitespace is ignored, and the input is plain ASCII.

    For lines = ["hello world", "foo bar baz", ""] the answer is 5: the first line has 2 words, the second has 3, and the empty line has none. A line made only of whitespace also counts 0, and an empty list gives 0.

    Approach: trim, skip blanks, split

    Handle one line at a time and add its word count to a running total. To count the words of a single line, cut it at every run of whitespace and count the pieces. Java's String.split does the cutting, but it has two habits that give wrong counts on messy input, so the line is cleaned up first.

    These results come from real calls:

    • "".split("\\s+").length is 1. Splitting an empty string gives an array holding one empty string, which would count as a word.
    • " ".split("\\s+").length is 0. A whitespace-only string is cut into nothing but empty pieces, and Java drops trailing empty pieces.
    • " a b".split("\\s+") is ["", "a", "b"], length 3. Leading whitespace produces an empty first piece, and that one is kept.

    Trimming the line removes the leading and trailing whitespace, so no empty piece can appear at either end. After that, the only remaining problem is the empty line, which is skipped explicitly. Every piece of a trimmed, non-empty line is a real word.

    Step by step

    1. Create total. An int starting at 0 holds the sum, so an empty list returns 0 without any special case.
    2. Loop over the lines with a for-each loop. The loop gives each entry as a String named line, and no index is needed.
    3. Trim the line into trimmed with line.trim(). Strings are immutable, so trim() returns a new string and leaves line unchanged.
    4. Skip blank lines. If trimmed.isEmpty(), continue jumps to the next line before any splitting happens. This covers both empty lines and whitespace-only lines, since the latter become empty after trimming.
    5. Add the word count. trimmed.split("\\s+") cuts the text at every run of whitespace, and .length is the number of pieces. Arrays use length without parentheses, unlike a string's length().
    6. Return total after the loop, so it runs once, when every line has been counted.

    The solution in Java

    class Solution {
        public int countWords(List<String> lines) {
            int total = 0;
            for (String line : lines) {
                String trimmed = line.trim();
                if (trimmed.isEmpty()) continue;
                total += trimmed.split("\\s+").length;
            }
            return total;
        }
    }
    

    The Java details worth a closer look:

    • The doubled backslash. The regular expression is \s+: \s matches one whitespace character and + means one or more. A backslash starts an escape sequence inside a Java string literal, so it is written twice: "\\s+".
    • split takes a regular expression. "a b".split(" ") has two spaces between the letters and returns three pieces, because every single space is a separator. "a b".split("\\s+") returns two, because the whole run is one separator.
    • Tabs count too. \s matches tabs as well as spaces, so " padded words\there " contains 3 words.
    • List needs an import. In a standalone file the class needs import java.util.List; (or java.util.*).

    Complexity

    Time: O(n), where n is the total number of characters in all lines. Trimming and splitting each line read it a constant number of times.

    Space: O(m), where m is the length of the longest line. trim() and split create a new string and an array of pieces for one line at a time, and these are garbage once the loop moves on.

    Edge cases and common mistakes

    • Skipping the trim. A line such as " a b" would count as 3 words instead of 2, because of the empty first piece.
    • Skipping the empty check. With only the trim, an empty line would add 1, since splitting "" returns one piece. Whitespace-only lines are fine either way, but the empty line is not.
    • Splitting on " ". Two spaces in a row, or a tab, give wrong counts. Use "\\s+".
    • An empty list. The loop runs zero times and the method returns 0.
    • Counting lines instead of words. lines.size() is the number of lines. Words need the inner count.

    Testing

    • ["hello world", "foo bar baz", ""] gives 5.
    • [" padded words\there "] gives 3.
    • [" ", "\t"] gives 0.
    • [] gives 0.
    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free