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

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

    I made a solution in Java 8 that is IMHO more readable.

    public String firstLetterCapitalWithSingleSpace(final String words) {
        return Stream.of(words.trim().split("\\s"))
        .filter(word -> word.length() > 0)
        .map(word -> word.substring(0, 1).toUpperCase() + word.substring(1))
        .collect(Collectors.joining(" "));
    }
    

    The Gist for this solution can be found here: https://gist.github.com/Hylke1982/166a792313c5e2df9d31

提交回复
热议问题