Creates a new String using the source string and formats it using title case. - Java java.lang

Java examples for java.lang:String New Line

Description

Creates a new String using the source string and formats it using title case.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String str = "this is a test";
        System.out.println(toTitleCase(str));
    }/*from   ww  w .  j a  va2s .  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();
    }
}

Related Tutorials