Is there a method for String conversion to Title Case?

Are there any built in methods available to convert a string into Title Case format?


Solution 1:

Apache Commons StringUtils.capitalize() or Commons Text WordUtils.capitalize()

e.g: WordUtils.capitalize("i am FINE") = "I Am FINE" from WordUtils doc

Solution 2:

There are no capitalize() or titleCase() methods in Java's String class. You have two choices:

  • using commons lang string utils.
 StringUtils.capitalize(null)  = null
 StringUtils.capitalize("")    = ""
 StringUtils.capitalize("cat") = "Cat"
 StringUtils.capitalize("cAt") = "CAt"
 StringUtils.capitalize("'cat'") = "'cat'"
  • write (yet another) static helper method toTitleCase()

Sample implementation

public static String toTitleCase(String input) {
    StringBuilder titleCase = new StringBuilder(input.length());
    boolean nextTitleCase = true;

    for (char c : input.toCharArray()) {
        if (Character.isSpaceChar(c)) {
            nextTitleCase = true;
        } else if (nextTitleCase) {
            c = Character.toTitleCase(c);
            nextTitleCase = false;
        }

        titleCase.append(c);
    }

    return titleCase.toString();
}

Testcase

    System.out.println(toTitleCase("string"));
    System.out.println(toTitleCase("another string"));
    System.out.println(toTitleCase("YET ANOTHER STRING"));

outputs:

String
Another String
YET ANOTHER STRING