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

后端 未结 30 1807
情深已故
情深已故 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条回答
  •  Happy的楠姐
    2020-11-22 02:25

    Use:

        String text = "jon skeet, miles o'brien, old mcdonald";
    
        Pattern pattern = Pattern.compile("\\b([a-z])([\\w]*)");
        Matcher matcher = pattern.matcher(text);
        StringBuffer buffer = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(buffer, matcher.group(1).toUpperCase() + matcher.group(2));
        }
        String capitalized = matcher.appendTail(buffer).toString();
        System.out.println(capitalized);
    

提交回复
热议问题