如何将字符串中每个单词的第一个字母大写,同时删除 Java 中的最终空格?

How to upper case every first letter of word in a string, meanwhile removing eventual whitespaces in Java?

如何将字符串中每个单词的第一个字母大写,同时删除 Java 中的最终空格?

private String name;

public String getName() {
    return name.replaceAll("\s+","")
        .substring(0, 1)
        .toUpperCase() + name.substring(1)
        .toLowerCase();
}

如果您想尽一切努力做到这一点,请使用像 Guava 这样的库。

在此处查看 CaseFormat 的文档:https://github.com/google/guava/wiki/StringsExplained#caseformat

如果我没有理解错你的要求,我想做如下:

public static void main(String[] args) {
        String input = "this is a Sample text";
        String[] tokens = input.split("\s+");
        StringBuilder output = new StringBuilder();
        for (String s : tokens) {
            output.append(s.trim().replaceFirst(String.valueOf(s.charAt(0)),
                    String.valueOf(Character.toUpperCase(s.charAt(0)))));
        }

        System.out.println(output.toString());//ThisIsASampleText
    }

注意:我没有考虑像,.;等常用的特殊字符分隔单词。如果你需要这些东西连同 space 请在拆分成单词时将它们添加到正则表达式中。