Capitalizes the first character of each word. - Android java.lang

Android examples for java.lang:String Case

Description

Capitalizes the first character of each word.

Demo Code

import android.util.Log;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Set;

public class Main{

    /**//from w  w w  .j ava 2s  .  c  o  m
     * Capitalizes the first character of each word.
     * Taken from: http://stackoverflow.com/questions/1892765/capitalize-first-char-of-each-word-in-a-string-java
     * 
     * @param string the string to be capitalized
     * @return the string once capitalized
     */
    public static String capitalizeString(String string) {
        char[] chars = string.toLowerCase(Locale.GERMAN).toCharArray();
        boolean found = false;
        for (int i = 0; i < chars.length; i++) {
            if (!found && Character.isLetter(chars[i])) {
                chars[i] = Character.toUpperCase(chars[i]);
                found = true;
            } else if (Character.isWhitespace(chars[i]) || chars[i] == '.'
                    || chars[i] == '\'') { // You can add other chars here
                found = false;
            }
        }
        return String.valueOf(chars);
    }

}

Related Tutorials