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

例子:

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

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

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


当前回答

来自Java 9+

你可以像这样使用String::replaceAll:

public static void upperCaseAllFirstCharacter(String text) {
    String regex = "\\b(.)(.*?)\\b";
    String result = Pattern.compile(regex).matcher(text).replaceAll(
            matche -> matche.group(1).toUpperCase() + matche.group(2)
    );

    System.out.println(result);
}

例子:

upperCaseAllFirstCharacter("hello this is Just a test");

输出

Hello This Is Just A Test

其他回答

这条适用于姓氏的情况……

使用不同类型的分隔符,并且它保持相同的分隔符:

jean-frederic -> jean-frederic jean frederic——> jean frederic

该代码与GWT客户端一起工作。

public static String capitalize (String givenString) {
    String Separateur = " ,.-;";
    StringBuffer sb = new StringBuffer(); 
    boolean ToCap = true;
    for (int i = 0; i < givenString.length(); i++) {
        if (ToCap)              
            sb.append(Character.toUpperCase(givenString.charAt(i)));
        else
            sb.append(Character.toLowerCase(givenString.charAt(i)));

        if (Separateur.indexOf(givenString.charAt(i)) >=0) 
            ToCap = true;
        else
            ToCap = false;
    }          
    return sb.toString().trim();
}  

我做了这个小类,可以用来大写一个句子中的每个单词。如果不是空格,可以更改字符串中的单词分隔符。

package com.ecnews.ecnews_v01.Helpers;

  public class Capitalize {

  String sentence;
  String separator = " ";

  public Capitalize(String sentence) {
    this.sentence = sentence;
  }

  public void setSeparator(String separator) {
    this.separator = separator;
  }

  public String getCapitalized() {
    StringBuilder capitalized = new StringBuilder("");
    for (String word : sentence.split(separator)) {
        capitalized.append(separator+Character.toUpperCase(word.charAt(0)) + word.substring(1));
    }
    return capitalized.toString().trim();
  }

}

例子:

String sourceName = new Capitalize("this is a test"). get资本化();

sourceName将是“This Is A Test”

下面是这个问题的Kotlin版本:

fun capitalizeFirstLetterOfEveryWord(text: String): String
{
    if (text.isEmpty() || text.isBlank())
    {
        return ""
    }

    if (text.length == 1)
    {
        return Character.toUpperCase(text[0]).toString()
    }

    val textArray = text.split(" ")
    val stringBuilder = StringBuilder()

    for ((index, item) in textArray.withIndex())
    {
        // If item is empty string, continue to next item
        if (item.isEmpty())
        {
            continue
        }

        stringBuilder
            .append(Character.toUpperCase(item[0]))

        // If the item has only one character then continue to next item because we have already capitalized it.
        if (item.length == 1)
        {
            continue
        }

        for (i in 1 until item.length)
        {
            stringBuilder
                .append(Character.toLowerCase(item[i]))
        }

        if (index < textArray.lastIndex)
        {
            stringBuilder
                .append(" ")
        }
    }

    return stringBuilder.toString()
}

如果你更喜欢番石榴……

String myString = ...;

String capWords = Joiner.on(' ').join(Iterables.transform(Splitter.on(' ').omitEmptyStrings().split(myString), new Function<String, String>() {
    public String apply(String input) {
        return Character.toUpperCase(input.charAt(0)) + input.substring(1);
    }
}));
public static String toTitleCase(String word){
    return Character.toUpperCase(word.charAt(0)) + word.substring(1);
}

public static void main(String[] args){
    String phrase = "this is to be title cased";
    String[] splitPhrase = phrase.split(" ");
    String result = "";

    for(String word: splitPhrase){
        result += toTitleCase(word) + " ";
    }
    System.out.println(result.trim());
}