Convert a String to Modified Camel Case in Java or Title Case as is otherwise called

takrishna picture takrishna · Jun 13, 2013 · Viewed 113.1k times · Source

I want to convert any string to modified Camel case or Title case using some predefined libraries than writing my own functions.

For example "HI tHiS is SomE Statement" to "Hi This Is Some Statement"

Regex or any standard library will help me.

I found certain library functions in eclipse like STRING.toCamelCase(); is there any such thing existing?

Answer

Florent Bayle picture Florent Bayle · Jun 13, 2013

You can easily write the method to do that :

  public static String toCamelCase(final String init) {
    if (init == null)
        return null;

    final StringBuilder ret = new StringBuilder(init.length());

    for (final String word : init.split(" ")) {
        if (!word.isEmpty()) {
            ret.append(Character.toUpperCase(word.charAt(0)));
            ret.append(word.substring(1).toLowerCase());
        }
        if (!(ret.length() == init.length()))
            ret.append(" ");
    }

    return ret.toString();
}