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

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

    From Java 9+

    you can use String::replaceAll like this :

    public static void upperCaseAllFirstCharacter(String text) {
        String regex = "\\b(.)(.*?)\\b";
        String result = Pattern.compile(regex).matcher(text).replaceAll(
                matche -> matche.group(1).toUpperCase() + matche.group(2)
        );
    
        System.out.println(result);
    }
    

    Example :

    upperCaseAllFirstCharacter("hello this is Just a test");
    

    Outputs

    Hello This Is Just A Test
    

提交回复
热议问题