How do I convert a string to title case in android?

Russ picture Russ · Sep 12, 2012 · Viewed 36.6k times · Source

I searched high and low but could only find indirect references to this type of question. When developing an android application, if you have a string which has been entered by the user, how can you convert it to title case (ie. make the first letter of each word upper case)? I would rather not import a whole library (such as Apache's WordUtils).

Answer

Codeversed picture Codeversed · Mar 4, 2015
     /**
     * Function to convert string to title case
     * 
     * @param string - Passed string 
     */
    public static String toTitleCase(String string) {

        // Check if String is null
        if (string == null) {
            
            return null;
        }

        boolean whiteSpace = true;
        
        StringBuilder builder = new StringBuilder(string); // String builder to store string
        final int builderLength = builder.length();

        // Loop through builder
        for (int i = 0; i < builderLength; ++i) {

            char c = builder.charAt(i); // Get character at builders position
            
            if (whiteSpace) {
                
                // Check if character is not white space
                if (!Character.isWhitespace(c)) {
                    
                    // Convert to title case and leave whitespace mode.
                    builder.setCharAt(i, Character.toTitleCase(c));
                    whiteSpace = false;
                }
            } else if (Character.isWhitespace(c)) {
                
                whiteSpace = true; // Set character is white space
            
            } else {
            
                builder.setCharAt(i, Character.toLowerCase(c)); // Set character to lowercase
            }
        }

        return builder.toString(); // Return builders text
    }