Java 将每个单词的第一个字母转换为大写

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22548704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:24:46  来源:igfitidea点击:

Converting first letter of each word to uppercase

java

提问by javaGeek

Does anyone know if there is another method other than WordUtils.capitalize()that converts the first letter of each word to upper case?

有谁知道除了WordUtils.capitalize()将每个单词的第一个字母转换为大写之外是否还有另一种方法?

采纳答案by PlasmaPower

You could use a method you create:

您可以使用您创建的方法:

String CapsFirst(String str) {
    String[] words = str.split(" ");
    StringBuilder ret = new StringBuilder();
    for(int i = 0; i < words.length; i++) {
        ret.append(Character.toUpperCase(words[i].charAt(0)));
        ret.append(words[i].substring(1));
        if(i < words.length - 1) {
            ret.append(' ');
        }
    }
    return ret.toString();
}

回答by Alaeddine

public static String caseFirst(String givenString) {
            String[] a= givenString.split(" ");
            StringBuffer s= new StringBuffer();
            for (int i = 0; i < a.length; i++) {
            s.append(Character.toUpperCase(a[i].charAt(0))).append(a[i].substring(1)).append(" ");
            }          
          return s.toString().trim();
        }