Java中是否内置了一个函数,使字符串中每个单词的第一个字符大写,而不影响其他字符?

例子:

乔恩·斯基特->乔恩·斯基特 miles o'Brien -> miles o'Brien (B仍然是大写,这排除了Title Case) 老麦当劳->

*(老麦当劳也会被发现,但我不指望它有那么聪明。)

快速浏览一下Java字符串文档就会发现只有toUpperCase()和toLowerCase(),它们当然没有提供所需的行为。当然,谷歌的结果主要是这两个函数。它看起来像一个已经被发明出来的轮子,所以问一下也无妨,这样我以后就可以用它了。


当前回答

intiCap的可重用方法:

    public class YarlagaddaSireeshTest{

    public static void main(String[] args) {
        String FinalStringIs = "";
        String testNames = "sireesh yarlagadda test";
        String[] name = testNames.split("\\s");

        for(String nameIs :name){
            FinalStringIs += getIntiCapString(nameIs) + ",";
        }
        System.out.println("Final Result "+ FinalStringIs);
    }

    public static String getIntiCapString(String param) {
        if(param != null && param.length()>0){          
            char[] charArray = param.toCharArray(); 
            charArray[0] = Character.toUpperCase(charArray[0]); 
            return new String(charArray); 
        }
        else {
            return "";
        }
    }
}

其他回答

试试这个:

 private String capitalizer(String word){

        String[] words = word.split(" ");
        StringBuilder sb = new StringBuilder();
        if (words[0].length() > 0) {
            sb.append(Character.toUpperCase(words[0].charAt(0)) + words[0].subSequence(1, words[0].length()).toString().toLowerCase());
            for (int i = 1; i < words.length; i++) {
                sb.append(" ");
                sb.append(Character.toUpperCase(words[i].charAt(0)) + words[i].subSequence(1, words[i].length()).toString().toLowerCase());
            }
        }
        return  sb.toString();
    }
String toBeCapped = "i want this sentence capitalized";

String[] tokens = toBeCapped.split("\\s");
toBeCapped = "";

for(int i = 0; i < tokens.length; i++){
    char capLetter = Character.toUpperCase(tokens[i].charAt(0));
    toBeCapped +=  " " + capLetter + tokens[i].substring(1);
}
toBeCapped = toBeCapped.trim();

worddutil .capitalize(str) (from apache common -text)

(注意:如果你需要“fOO BAr”变成“fOO BAr”,那么用大写的(..)代替)

1. Java 8流

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(" "));
}

例子:

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

对于foo bAR到foo bAR,替换map()方法如下:

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

2. 字符串()(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));
}

例子:

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文本

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

titlecase:

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

有关详细信息,请查看本教程。

我只想通过仅使用Java代码为该问题添加一个替代解决方案。 没有额外的库

public String Capitalize(String str) {

            String tt = "";
            String tempString = "";
            String tempName = str.trim().toLowerCase();
            String[] tempNameArr = tempName.split(" ");
            System.out.println("The size is " + tempNameArr.length);
            if (tempNameArr.length > 1) {
                for (String t : tempNameArr) {
                    tt += Capitalize(t);
                    tt += " ";
                }
                tempString  = tt;
            } else {
                tempString = tempName.replaceFirst(String.valueOf(tempName.charAt(0)), String.valueOf(tempName.charAt(0)).toUpperCase());
            }
            return tempString.trim();
        }