字符串示例
one thousand only
two hundred
twenty
seven
我如何改变一个大写字母的字符串的第一个字符,而不改变任何其他字母的情况?
更改之后应该是:
One thousand only
Two hundred
Twenty
Seven
注意:我不想使用apache.commons.lang.WordUtils来做这件事。
字符串示例
one thousand only
two hundred
twenty
seven
我如何改变一个大写字母的字符串的第一个字符,而不改变任何其他字母的情况?
更改之后应该是:
One thousand only
Two hundred
Twenty
Seven
注意:我不想使用apache.commons.lang.WordUtils来做这件事。
当前回答
如果你只想大写一个名为input的字符串的第一个字母,其余的保持不变:
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
现在输出将有您想要的内容。在使用此方法之前,请检查您的输入至少是一个字符,否则将会出现异常。
其他回答
给定输入字符串:
Character.toUpperCase(input.charAt(0)) + input.substring(1).toLowerCase()
如果你只想大写一个名为input的字符串的第一个字母,其余的保持不变:
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
现在输出将有您想要的内容。在使用此方法之前,请检查您的输入至少是一个字符,否则将会出现异常。
1. 使用字符串的substring()方法
public static String capitalize(String str) {
if(str== null || str.isEmpty()) {
return str;
}
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
现在只需调用capitalize()方法将字符串的第一个字母转换为大写字母:
System.out.println(capitalize("stackoverflow")); // Stackoverflow
System.out.println(capitalize("heLLo")); // HeLLo
System.out.println(capitalize(null)); // null
2. Apache Commons Lang
Commons Lang中的StringUtils类提供了capitalize()方法,该方法也可用于此目的:
System.out.println(StringUtils.capitalize("apache commons")); // Apache commons
System.out.println(StringUtils.capitalize("heLLO")); // HeLLO
System.out.println(StringUtils.uncapitalize(null)); // null
将以下依赖项添加到pom.xml文件中(仅适用于Maven):
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
下面是一篇详细解释这两种方法的文章。
把所有的东西加在一起,在字符串的开头修剪出额外的空白是一个好主意。否则,.substring(0, 1)。toUpperCase将尝试大写一个空白。
public String capitalizeFirstLetter(String original) {
if (original == null || original.length() == 0) {
return original;
}
return original.trim().substring(0, 1).toUpperCase() + original.substring(1);
}
class Test {
public static void main(String[] args) {
String newString="";
String test="Hii lets cheCk for BEING String";
String[] splitString = test.split(" ");
for(int i=0; i<splitString.length; i++){
newString= newString+ splitString[i].substring(0,1).toUpperCase()
+ splitString[i].substring(1,splitString[i].length()).toLowerCase()+" ";
}
System.out.println("the new String is "+newString);
}
}