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

后端 未结 30 1893
情深已故
情深已故 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:45

    public static String toTitleCase(String word){
        return Character.toUpperCase(word.charAt(0)) + word.substring(1);
    }
    
    public static void main(String[] args){
        String phrase = "this is to be title cased";
        String[] splitPhrase = phrase.split(" ");
        String result = "";
    
        for(String word: splitPhrase){
            result += toTitleCase(word) + " ";
        }
        System.out.println(result.trim());
    }
    

提交回复
热议问题