Java String Capitalize capitalize(String pString)

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

Description

Makes the first letter of a String uppercase.

License

Open Source License

Parameter

Parameter Description
pString The string to capitalize

Return

The capitalized string, or null, if a null argument was given.

Declaration

public static String capitalize(String pString) 

Method Source Code

//package com.java2s;

public class Main {
    /**//from w  w  w.java  2  s .co m
     * Makes the Nth letter of a String uppercase. If the index is outside the
     * the length of the argument string, the argument is simply returned.
     *
     * @param pString The string to capitalize
     * @param pIndex  The base-0 index of the char to capitalize.
     * @return The capitalized string, or null, if a null argument was given.
     */
    public static String capitalize(String pString, int pIndex) {
        if (pIndex < 0) {
            throw new IndexOutOfBoundsException("Negative index not allowed: " + pIndex);
        }
        if (pString == null || pString.length() <= pIndex) {
            return pString;
        }

        // This is the fastest method, according to my tests

        // Skip array duplication if allready capitalized
        if (Character.isUpperCase(pString.charAt(pIndex))) {
            return pString;
        }

        // Convert to char array, capitalize and create new String
        char[] charArray = pString.toCharArray();
        charArray[pIndex] = Character.toUpperCase(charArray[pIndex]);
        return new String(charArray);

        /**
         StringBuilder buf = new StringBuilder(pString);
         buf.setCharAt(pIndex, Character.toUpperCase(buf.charAt(pIndex)));
         return buf.toString();
         //*/

        /**
         return pString.substring(0, pIndex)
         +  Character.toUpperCase(pString.charAt(pIndex))
         + pString.substring(pIndex + 1);
         //*/
    }

    /**
     * Makes the first letter of a String uppercase.
     *
     * @param pString The string to capitalize
     * @return The capitalized string, or null, if a null argument was given.
     */
    public static String capitalize(String pString) {
        return capitalize(pString, 0);
    }

    /**
     * Converts a string to uppercase.
     *
     * @param pString the string to convert
     * @return the string converted to uppercase, or null if the argument was
     *         null.
     */
    public static String toUpperCase(String pString) {
        if (pString != null) {
            return pString.toUpperCase();
        }
        return null;
    }
}

Related

  1. capitalize(String name)
  2. capitalize(String name)
  3. capitalize(String orig)
  4. capitalize(String original)
  5. capitalize(String propertyName)
  6. capitalize(String s)
  7. capitalize(String s)
  8. capitalize(String s)
  9. capitalize(String s)