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 Nth letter of a String uppercase . If the index is outside the the length of the argument string the argument is simply returned .