How to capitalize the first character of each word in a string
Is there a function built into Java that capitalizes the first character of each word in a String, and does not affect the others?
Examples:
jon skeet
-> Jon Skeet
miles o'Brien
-> Miles O'Brien
(B remains capital, this rules out Title Case) old mcdonald
-> Old Mcdonald
* *( Old McDonald
would be find too, but I don't expect it to be THAT smart.)
A quick look at the Java String Documentation reveals only toUpperCase()
and toLowerCase()
, which of course do not provide the desired behavior. Naturally, Google results are dominated by those two functions. It seems like a wheel that must have been invented already, so it couldn't hurt to ask so I can use it in the future.
WordUtils.capitalize(str)
(from apache commons-text)
(Note: if you need "fOO BAr"
to become "Foo Bar"
, then use capitalizeFully(..)
instead)
如果你只是担心第一个字母大写的第一个字母:
private String capitalize(final String line) {
return Character.toUpperCase(line.charAt(0)) + line.substring(1);
}
以下方法将所有字母转换为大写/小写,具体取决于它们在空间或其他特殊字符附近的位置。
public static String capitalizeString(String string) {
char[] chars = string.toLowerCase().toCharArray();
boolean found = false;
for (int i = 0; i < chars.length; i++) {
if (!found && Character.isLetter(chars[i])) {
chars[i] = Character.toUpperCase(chars[i]);
found = true;
} else if (Character.isWhitespace(chars[i]) || chars[i]=='.' || chars[i]==''') { // You can add other chars here
found = false;
}
}
return String.valueOf(chars);
}
链接地址: http://www.djcxy.com/p/75356.html
上一篇: 在PHP中NOW()函数
下一篇: 如何大写字符串中每个单词的第一个字符