Java String Capitalize capitalize(String s)

Here you can find the source of capitalize(String s)

Description

Capitalizes all the words of a string.

License

Open Source License

Parameter

Parameter Description
s a string (can be null)

Return

the capitalized string, or null if the original string was null

Declaration

public static String capitalize(String s) 

Method Source Code

//package com.java2s;
/******************************************************************************
 * Copyright (c) 2008-2013, Linagora// w  w w . j a v a2 s . c  o m
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *       Linagora - initial API and implementation
 *******************************************************************************/

public class Main {
    /**
     * Capitalizes all the words of a string.
     * @param s a string (can be null)
     * @return the capitalized string, or null if the original string was null
     */
    public static String capitalize(String s) {

        if (s == null)
            return null;

        StringBuilder sb = new StringBuilder();
        for (String part : s.split("\\s")) {
            part = part.trim();
            if (part.length() == 0)
                continue;

            if (part.length() == 1)
                part = part.toUpperCase();
            else
                part = part.substring(0, 1).toUpperCase() + part.substring(1).toLowerCase();

            sb.append(part + " ");
        }

        return sb.toString().trim();
    }
}

Related

  1. capitalize(String s)
  2. capitalize(String s)
  3. capitalize(String s)
  4. capitalize(String s)
  5. capitalize(String s)
  6. capitalize(String s)
  7. capitalize(String s, char delimiter)
  8. capitalize(String s, String fullstring)
  9. capitalize(String source)