Capitalize the first letter of all words in a String
This is a cool little problem that needs Java8, and regex. ... promise.

First up, the Pattern.splitAsStream(...) method is new in Java8, and converts a string in to a stream of substrings, depending on the pattern, so, what's the pattern?

Well, the pattern is to match the beginning of any word that needs to be capitalized. Your code currently finds characters, after whitespace, but that is, as you admit, too naive. Words that need capitalization are things like:


This is 'quoted' -> This Is 'Quoted'
This has-joined-words -> This Has-Joined-Words
This should not 1800not1337 -> This Should Not 1800not1337


and so on.

So, your code would not deal well with the above examples.... but, how can it be better?

private static final Pattern bound = Pattern.compile("\\b(?=\\w)");


The above regular expression looks for a word-boundary that is followed by a character (where "a character" is a letter, digit, or underscore).

Then, you have a sequence of sentence parts that need captialization, and it can be streamed easily:

private static final Pattern bound = Pattern.compile("\\b(?=\\w)");

private static final String ucFirst(String input) {
    return input.substring(0,  1).toUpperCase() + input.substring(1);
};

public static String titleize(final String input) {
    return bound.splitAsStream(input)
          .map(StringCap::ucFirst)
          .collect(Collectors.joining());
}


You can see this running here: http://ideone.com/ilmBqi



Note: Using Java7 versions of Pattern matchers, it is also actually quite easy.... Consider this pattern, which stores the first-character as a pattern group, and then the "traditional" matching replacement loop:

private static final Pattern bound = Pattern.compile("\\b(\\w)");

public static String titleize(final String input) {
    StringBuffer sb = new StringBuffer(input.length());
    Matcher mat = bound.matcher(input);
    while (mat.find()) {
        mat.appendReplacement(sb, mat.group().toUpperCase());
    }
    mat.appendTail(sb);
    return sb.toString();
}


The above is able to capitalize the words in the same output as the Java8 version above.