在Char中将CharSequence的第一个字母改为大写

yoa*_*str 7 java string android uppercase

它可能看起来很简单,但它有很多错误,我试过这种方式:

 String s = gameList[0].toString();
s.replaceFirst(String.valueOf(s.charAt(0)),String.valueOf(Character.toUpperCase(s.charAt(0))) );
Run Code Online (Sandbox Code Playgroud)

它会引发异常

我的另一个尝试是:

String s = gameList[0].toString();
char c = Character.toUpperCase(gameList[0].charAt(0));
gameList[0] = s.subSequence(1, s.length());
Run Code Online (Sandbox Code Playgroud)

这个也引发了例外

Pen*_*m10 13

/**
 * returns the string, the first char lowercase
 *
 * @param target
 * @return
 */
public final static String asLowerCaseFirstChar(final String target) {

    if ((target == null) || (target.length() == 0)) {
        return target; // You could omit this check and simply live with an
                       // exception if you like
    }
    return Character.toLowerCase(target.charAt(0))
            + (target.length() > 1 ? target.substring(1) : "");
}

/**
 * returns the string, the first char uppercase
 *
 * @param target
 * @return
 */
public final static String asUpperCaseFirstChar(final String target) {

    if ((target == null) || (target.length() == 0)) {
        return target; // You could omit this check and simply live with an
                       // exception if you like
    }
    return Character.toUpperCase(target.charAt(0))
            + (target.length() > 1 ? target.substring(1) : "");
}
Run Code Online (Sandbox Code Playgroud)


小智 9

...或者在数组中完成所有操作.这是类似的东西.

    String titleize(String source){
        boolean cap = true;
        char[]  out = source.toCharArray();
        int i, len = source.length();
        for(i=0; i<len; i++){
            if(Character.isWhitespace(out[i])){
                cap = true;
                continue;
            }
            if(cap){
                out[i] = Character.toUpperCase(out[i]);
                cap = false;
            }
        }
        return new String(out);
    }
Run Code Online (Sandbox Code Playgroud)