是否有将字符串转换为标题大小写的方法?
2022-08-31 09:16:29
是否有任何内置方法可用于将字符串转换为标题大小写格式?
Apache Commons StringUtils.capitalize() 或 Commons Text WordUtils.capitalize()
例如:来自WordUtils文档WordUtils.capitalize("i am FINE") = "I Am FINE"
Java 的 String 类中没有 capitalize() 或 titleCase() 方法。您有两种选择:
StringUtils.capitalize(null) = null
StringUtils.capitalize("") = ""
StringUtils.capitalize("cat") = "Cat"
StringUtils.capitalize("cAt") = "CAt"
StringUtils.capitalize("'cat'") = "'cat'"
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