Count Lines, Words and Characters

easy Files and I/O

Problem

Read the whole input. Print three lines: lines: <number of lines>, words: <number of words separated by spaces or tabs>, characters: <number of characters, not counting the line breaks>. Count empty lines as lines, too.

Constraints

  • The input has at least one line

Examples

Input

hello world
java is fun

Output

lines: 2
words: 5
characters: 22

Solutions

Best approachTime O(n)Space O(1)

This is the idea of the Unix wc program. A word is a group of non-space characters. For an empty line, split would give one empty word in some languages, so we check for it.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Count text statistics.
 * Input   : Many lines of text.
 * Output  : Three lines.
 * Approach: One pass over the lines.
 * Time    : O(n)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static String[] solve(String[] lines) {
        int words = 0;
        int characters = 0;

        for (String line : lines) {
            // Step 1: Count the characters of the line (without the line break).
            characters += line.length();

            // Step 2: Count the words. split on spaces and tabs ignores extra spaces after trim. An empty line has no words.
            String trimmed = line.trim();
            if (!trimmed.isEmpty()) {
                words += trimmed.split("\\s+").length;
            }
        }

        // Step 3: The number of lines is the number of array elements.
        return new String[] {"lines: " + lines.length, "words: " + words, "characters: " + characters};
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        java.util.List<String> all = new java.util.ArrayList<>();
        while (scanner.hasNextLine()) {
            all.add(scanner.nextLine());
        }
        String[] lines = all.toArray(new String[0]);
        System.out.println(String.join("\n", solve(lines)));
    }
}
Hints (1)
  1. What does split give for an empty line?