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

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

    Try this very simple way

    example givenString="ram is good boy"

    public static String toTitleCase(String givenString) {
        String[] arr = givenString.split(" ");
        StringBuffer sb = new StringBuffer();
    
        for (int i = 0; i < arr.length; i++) {
            sb.append(Character.toUpperCase(arr[i].charAt(0)))
                .append(arr[i].substring(1)).append(" ");
        }          
        return sb.toString().trim();
    }  
    

    Output will be: Ram Is Good Boy

提交回复
热议问题