Java String Capitalize capitalize(String string)

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

Description

Method that converts first char of given string to upper case and rest of charts - to lower case.

License

Apache License

Parameter

Parameter Description
string A string to be converted

Return

the specified string where first char is capitalized

Declaration

public static String capitalize(String string) 

Method Source Code

//package com.java2s;
/*/*  ww  w  . ja va 2  s. com*/
 * Copyright 2011-2012 Maxim Dominichenko
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

public class Main {
    /**
     * Method that converts first char of given string to upper case and rest of charts - to lower case.
     *
     * @param string A string to be converted
     * @return the specified string where first char is capitalized
     */
    public static String capitalize(String string) {
        String result;
        if (!isHollow(string)) {
            string = string.toLowerCase();
            result = Character.toUpperCase(string.charAt(0)) + string.substring(1);
        } else
            result = "";
        return result;
    }

    /**
     * Helper to check if the String is {@code null} or empty 
     * or contains any kind of spaces ("\s" regexp pattern) only.
     *
     * @param string A string to be checked
     * @return {@code true} if is not {@code null} and contains anything but whitespaces. {@code false} otherwise.
     */
    public static boolean isHollow(String string) {
        return isEmpty(string) || string.matches("^\\s+$");
    }

    /**
     * Helper to check if the String is {@code null} or empty.<br/>
     * {@link String#isEmpty()} is not static and therefore require additional check for {@code null}.
     *
     * @param string A string to be checked
     * @return {@code true} if is not {@code null} and is not empty. {@code false} otherwise.
     */
    public static boolean isEmpty(String string) {
        return string == null || string.length() == 0;
    }
}

Related

  1. capitalize(String str, char[] wordDelimiters)
  2. capitalize(String str, String delim)
  3. capitalize(String str, String delimiter)
  4. capitalize(String string)
  5. capitalize(String string)
  6. capitalize(String string)
  7. capitalize(String string)
  8. capitalize(String string)
  9. capitalize(String string)