[英]How to make String first letter capital and others small
I am trying to convert String first letter as capital and remaining should be small.我正在尝试将字符串的第一个字母转换为大写字母,剩余的应该很小。 I tried below code.
我试过下面的代码。 It's working fine with convert first letter capital but it's converting remaining letter as small.
它可以很好地转换首字母大写,但它会将剩余的字母转换为小写字母。
String str = "hiGh";
// capitalize first letter
String output = str.substring(0, 1).toUpperCase() + str.substring(1)
Output should be: High
Output 应该是:
High
You could manipulate the characters of a String
to make sure that only the first one is uppercase,您可以操纵
String
的字符以确保只有第一个是大写的,
String capitalizeFirstOf(String s){
char[] chars = s.toCharArray();
for (int i=0; i<s.length(); i++){
if (i==0){
chars[i] = Character.toUpperCase(chars[i]);
}else{
chars[i] = Character.toLowerCase(chars[i]);
}
}
return new String(chars);
}
You need to change the later substring to the lowercase.需要把后面的substring改成小写。 Use the following code:
使用以下代码:
String name = "hiGH";
name = name.substring(0,1).toUpperCase() + name.substring(1).toLowerCase();
If your doing much string converting i would recomend using a libary like: apache commons 3如果您进行大量字符串转换,我建议您使用以下库: apache commons 3
They have eg UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize
etc.他们有例如
UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize
等。
So you don't have to put you time on simple string methods.所以你不必把时间花在简单的字符串方法上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.