Java: Word statistics

Split a line into words, then measure and reshape them.

What to build

A program that counts the words of a line, finds the longest, and prints it in title case.

Requirements

  • Read one line of words separated by one or more spaces.
  • Print words: N, longest: W (the first of the longest words) and title: T, the words in Title Case joined by single spaces.
  • For a line with no words, print words: 0 and nothing else.

Input

One line.

Output

Three lines, or one.

Constraints

At most 500 characters, letters and spaces only.

Example

Input:

the quick brown fox

Output:

words: 4
longest: quick
title: The Quick Brown Fox

Why it works

Splitting on the pattern for one or more spaces ignores extra spaces, a strict greater-than comparison keeps the first of equally long words, and substring separates each word's first letter from the rest.

Examples

Example 1 · Input
the quick brown fox
Expected output
words: 4
longest: quick
title: The Quick Brown Fox
Example 2 · Input
  hello    WORLD
Expected output
words: 2
longest: hello
title: Hello World

Hints

Hint 1

line.trim().split("\\s+") splits on runs of spaces.

Hint 2

Capitalise a word with its first letter in upper case and the rest in lower case.

Solution

Show one correct solution (try it yourself first)
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String line = in.hasNextLine() ? in.nextLine().trim() : "";
        if (line.isEmpty()) {
            System.out.println("words: 0");
            return;
        }
        String[] words = line.split("\\s+");
        String longest = words[0];
        StringBuilder title = new StringBuilder();
        for (String w : words) {
            if (w.length() > longest.length()) longest = w;
            if (title.length() > 0) title.append(' ');
            title.append(w.substring(0, 1).toUpperCase()).append(w.substring(1).toLowerCase());
        }
        System.out.println("words: " + words.length);
        System.out.println("longest: " + longest);
        System.out.println("title: " + title);
    }
}

Lesson: Strings and StringBuilder →