Returns title case of string. - Android java.lang

Android examples for java.lang:String Case

Description

Returns title case of string.

Demo Code

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Iterator;
import java.util.Locale;
import java.util.UUID;

public class Main{

    /**/*w  w w .ja  v  a 2s . c o m*/
     * Returns title case of string.
     *
     * @param string input
     * @return titleCase string
     */
    public static String titleCase(String string) {
        StringBuilder builder = new StringBuilder();

        // split into words
        String[] parts = string.split("\\s+");

        // each word
        for (String part : parts) {
            if (builder.length() > 0) {
                builder.append(' ');
            }
            if (part.length() > 0) {
                builder.append(Character.toUpperCase(part.charAt(0)));
            }
            if (part.length() > 1) {
                builder.append(part.substring(1)
                        .toLowerCase(Locale.ENGLISH));
            }
        }

        return builder.toString();
    }

}

Related Tutorials