Java String Title Case toTitleCase(String name)

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

Description

Changes the each first letter of a word to upper case and rest of the strings to lower case

License

Open Source License

Parameter

Parameter Description
name name to be modified.

Return

the string in the title case.

Declaration

public static String toTitleCase(String name) 

Method Source Code

//package com.java2s;
/*/*from  w  w  w .j  av  a  2s.c o  m*/
 * Copyright (c) 2006-2010 Nokia Corporation and/or its subsidiary(-ies). 
 * All rights reserved.
 * This component and the accompanying materials are made available
 * under the terms of "Eclipse Public License v1.0"
 * which accompanies this distribution, and is available
 * at the URL "http://www.eclipse.org/legal/epl-v10.html".
 *
 * Initial Contributors:
 * Nokia Corporation - initial contribution.
 *
 * Contributors:
 *
 * Description:
 *
 */

public class Main {
    /**
     * Changes the each first letter of a word to upper case and rest of the
     * strings to lower case
     * 
     * @param name name to be modified.
     * @return the string in the title case.
     */
    public static String toTitleCase(String name) {
        if (name == null) {
            return null;
        }
        String result = name.substring(0, 1).toUpperCase();
        for (int i = 1; i < name.length(); i++) {
            if (name.substring(i - 1, i).contains(" ")
                    && (name.length() > i + 4)
                    && !name.substring(i, i + 4).equalsIgnoreCase("and "))
                result = result + name.substring(i, i + 1).toUpperCase();
            else
                result = result + name.substring(i, i + 1).toLowerCase();
        }
        return result;
    }
}

Related

  1. toTitleCase(final String text)
  2. toTitleCase(String givenString)
  3. toTitleCase(String input)
  4. toTitleCase(String input, boolean eachWord)
  5. toTitleCase(String inputStr)
  6. toTitleCase(String original)
  7. toTitleCase(String original)
  8. toTitleCase(String s)
  9. toTitleCase(String s)