This question already has an answer here:
这个问题在这里已有答案:
- String conversion to Title Case 15 answers
- How to capitalize the first character of each word in a string 42 answers
字符串转换为Title Case 15答案
如何将字符串中每个单词的第一个字符大写42个答案
I have multiple strings in upper case:
我有大写的多个字符串:
JAMES SMITH, NAVIN HEMANT SIGNH, LALA UTRIZER
詹姆斯史密斯,NAVIN HEMANT SIGNH,LALA UTRIZER
How can I transform these strings to:
如何将这些字符串转换为:
James Smith, Navin Hemant Signh, Lala Utrizer in java?
詹姆斯史密斯,Navin Hemant Signh,Lala Utrizer在java?
Please help.
2 个解决方案
#1
2
Try something like this:
尝试这样的事情:
String values = "JAMES SMITH, NAVIN HEMANT SIGNH, LALA UTRIZER";
if (values != null && !values.isEmpty()) {
final StringBuilder fixedCaseBuilder = new StringBuilder(values.length()+1);
for (final String word : values.split(" ")) {
if (!word.isEmpty()) {
fixedCaseBuilder.append(Character.toUpperCase(word.charAt(0)));
fixedCaseBuilder.append(word.substring(1, word.length()).toLowerCase());
}
fixedCaseBuilder.append(' ');
}
fixedCaseBuilder.setLength(fixedCaseBuilder.length()-1);
final String result = fixedCaseBuilder.toString();
}
#2
1
If you can choose what libraries to use, I would advise WordUtils from Apache Commons Utils. It has a method capitalizeFully(String s), which takes a String and capitalize the first letter of every word.
如果您可以选择使用哪些库,我建议使用Apache Commons Utils中的WordUtils。它有一个方法capitalizeFully(String s),它接受一个String并将每个单词的第一个字母大写。
#1
2
Try something like this:
尝试这样的事情:
String values = "JAMES SMITH, NAVIN HEMANT SIGNH, LALA UTRIZER";
if (values != null && !values.isEmpty()) {
final StringBuilder fixedCaseBuilder = new StringBuilder(values.length()+1);
for (final String word : values.split(" ")) {
if (!word.isEmpty()) {
fixedCaseBuilder.append(Character.toUpperCase(word.charAt(0)));
fixedCaseBuilder.append(word.substring(1, word.length()).toLowerCase());
}
fixedCaseBuilder.append(' ');
}
fixedCaseBuilder.setLength(fixedCaseBuilder.length()-1);
final String result = fixedCaseBuilder.toString();
}
#2
1
If you can choose what libraries to use, I would advise WordUtils from Apache Commons Utils. It has a method capitalizeFully(String s), which takes a String and capitalize the first letter of every word.
如果您可以选择使用哪些库,我建议使用Apache Commons Utils中的WordUtils。它有一个方法capitalizeFully(String s),它接受一个String并将每个单词的第一个字母大写。