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

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

    1. Java 8 Streams

    public static String capitalizeAll(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }
    
        return Arrays.stream(str.split("\\s+"))
                .map(t -> t.substring(0, 1).toUpperCase() + t.substring(1))
                .collect(Collectors.joining(" "));
    }
    

    Examples:

    System.out.println(capitalizeAll("jon skeet")); // Jon Skeet
    System.out.println(capitalizeAll("miles o'Brien")); // Miles O'Brien
    System.out.println(capitalizeAll("old mcdonald")); // Old Mcdonald
    System.out.println(capitalizeAll(null)); // null
    

    For foo bAR to Foo Bar, replace the map() method with the following:

    .map(t -> t.substring(0, 1).toUpperCase() + t.substring(1).toLowerCase())
    

    2. String.replaceAll() (Java 9+)

    ublic static String capitalizeAll(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }
    
        return Pattern.compile("\\b(.)(.*?)\\b")
                .matcher(str)
                .replaceAll(match -> match.group(1).toUpperCase() + match.group(2));
    }
    

    Examples:

    System.out.println(capitalizeAll("12 ways to learn java")); // 12 Ways To Learn Java
    System.out.println(capitalizeAll("i am atta")); // I Am Atta
    System.out.println(capitalizeAll(null)); // null
    

    3. Apache Commons Text

    System.out.println(WordUtils.capitalize("love is everywhere")); // Love Is Everywhere
    System.out.println(WordUtils.capitalize("sky, sky, blue sky!")); // Sky, Sky, Blue Sky!
    System.out.println(WordUtils.capitalize(null)); // null
    

    For titlecase:

    System.out.println(WordUtils.capitalizeFully("fOO bAR")); // Foo Bar
    System.out.println(WordUtils.capitalizeFully("sKy is BLUE!")); // Sky Is Blue!
    

    For details, checkout this tutorial.

提交回复
热议问题