是否有将字符串转换为标题大小写的方法?

2022-08-31 09:16:29

是否有任何内置方法可用于将字符串转换为标题大小写格式?


答案 1

Apache Commons StringUtils.capitalize() 或 Commons Text WordUtils.capitalize()

例如:来自WordUtils文档WordUtils.capitalize("i am FINE") = "I Am FINE"


答案 2

Java 的 String 类中没有 capitalize() 或 titleCase() 方法。您有两种选择:

 StringUtils.capitalize(null)  = null
 StringUtils.capitalize("")    = ""
 StringUtils.capitalize("cat") = "Cat"
 StringUtils.capitalize("cAt") = "CAt"
 StringUtils.capitalize("'cat'") = "'cat'"
  • 将(又一个)静态帮助器方法写入TitleCase()

示例实现

public static String toTitleCase(String input) {
    StringBuilder titleCase = new StringBuilder(input.length());
    boolean nextTitleCase = true;

    for (char c : input.toCharArray()) {
        if (Character.isSpaceChar(c)) {
            nextTitleCase = true;
        } else if (nextTitleCase) {
            c = Character.toTitleCase(c);
            nextTitleCase = false;
        }

        titleCase.append(c);
    }

    return titleCase.toString();
}

测试用例

    System.out.println(toTitleCase("string"));
    System.out.println(toTitleCase("another string"));
    System.out.println(toTitleCase("YET ANOTHER STRING"));

输出:

String
Another String
YET ANOTHER STRING