How to capitalize the first character of each word in a string

后端 未结 30 1435
情深已故
情深已故 2020-11-22 02:08

Is there a function built into Java that capitalizes the first character of each word in a String, and does not affect the others?

Examples:

  • jon
30条回答
  •  死守一世寂寞
    2020-11-22 02:32

    String toUpperCaseFirstLetterOnly(String str) {
        String[] words = str.split(" ");
        StringBuilder ret = new StringBuilder();
        for(int i = 0; i < words.length; i++) {
            ret.append(Character.toUpperCase(words[i].charAt(0)));
            ret.append(words[i].substring(1));
            if(i < words.length - 1) {
                ret.append(' ');
            }
        }
        return ret.toString();
    }
    

提交回复
热议问题