Java - Write code to convert string to Title Case

Requirements

Write code to convert string to Title Case

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String str = "this is a test from book2s.com";
        System.out.println(toTitleCase(str));
    }/*from  w  w  w.  j a  va 2 s. c  om*/

    public static String toTitleCase(String str) {

        if (str == null) {
            return null;
        }

        boolean space = true;
        StringBuilder builder = new StringBuilder(str);
        final int len = builder.length();

        for (int i = 0; i < len; ++i) {
            char c = builder.charAt(i);
            if (space) {
                if (!Character.isWhitespace(c)) {
                    // Convert to title case and switch out of whitespace mode.
                    builder.setCharAt(i, Character.toTitleCase(c));
                    space = false;
                }
            } else if (Character.isWhitespace(c)) {
                space = true;
            } else {
                builder.setCharAt(i, Character.toLowerCase(c));
            }
        }

        return builder.toString();
    }
}