Write code to Capitalizes a String changing the first letter to title case as per Character#toTitleCase(char) . - Java java.lang

Java examples for java.lang:String Capitalize

Requirements

Write code to Capitalizes a String changing the first letter to title case as per Character#toTitleCase(char) .

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String str = "java2s.com";
        System.out.println(capitalize(str));
    }/*  w  w  w . jav  a 2 s.  c o  m*/

    /**
     * <p>Capitalizes a String changing the first letter to title case as
     * per {@link Character#toTitleCase(char)}. No other letters are changed.</p>
     *
     * <pre>
     * capitalize(null)  = null
     * capitalize("")    = ""
     * capitalize("cat") = "Cat"
     * capitalize("cAt") = "CAt"
     * </pre>
     *
     * @param str  the String to capitalize, may be null
     * @return the capitalized String, <code>null</code> if null String input
     * @see #uncapitalize(String)
     * @since 2.0
     */
    public static String capitalize(String str) {
        int strLen;
        if (str == null || (strLen = str.length()) == 0) {
            return str;
        }
        return new StringBuffer(strLen)
                .append(Character.toTitleCase(str.charAt(0)))
                .append(str.substring(1)).toString();
    }
}

Related Tutorials