Java String Title Case toTitleCase(String title)

Here you can find the source of toTitleCase(String title)

Description

Converts words and multiple words to lowercase and Uppercase on first letter only E.g.

License

Open Source License

Declaration

public static String toTitleCase(String title) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**/*from   w  ww  . j  a  v  a2  s. c  om*/
     * Converts words and multiple words to lowercase and Uppercase on first
     * letter only E.g. daniel to Daniel, the monkeys to The Monkeys, BOB to
     * Bob. Allows apostrophes to be in words. Handles multiple words.
     * 
     * @testedby {@link StrUtilsTest#testToTitleCase1()}
     */
    public static String toTitleCase(String title) {
        if (title.length() < 2)
            return title.toUpperCase();
        StringBuilder sb = new StringBuilder(title.length());
        boolean goUp = true;
        for (int i = 0, n = title.length(); i < n; i++) {
            char c = title.charAt(i);
            if (Character.isLetterOrDigit(c) || c == '\'') {
                if (goUp) {
                    sb.append(Character.toUpperCase(c));
                    goUp = false;
                } else {
                    sb.append(Character.toLowerCase(c));
                }
            } else {
                sb.append(c);
                goUp = true;
            }
        }
        return sb.toString();
    }

    /**
     * Convenience for peeking at a character which might be beyond the end of
     * the sequence.
     * 
     * @param chars
     * @param i
     * @return the char at index i, if within range, or 0 otherwise.
     */
    public static char charAt(CharSequence chars, int i) {
        return i < chars.length() ? chars.charAt(i) : 0;
    }
}

Related

  1. toTitleCase(String str)
  2. toTitleCase(String str)
  3. toTitleCase(String string)
  4. toTitleCase(String string)
  5. toTitleCase(String text)
  6. toTitleCase2(String string, String separators)
  7. toTitleCaseIdentifier(String formStr)