如何在Java中大写字符串的第一个字母? [英] How to capitalize the first letter of a String in Java?
问题描述
我正在使用Java从用户那里获得 String
输入。我想把这个输入的第一个字母大写。
I am using Java to get a String
input from the user. I am trying to make the first letter of this input capitalized.
我试过这个:
String name;
BufferedReader br = new InputStreamReader(System.in);
String s1 = name.charAt(0).toUppercase());
System.out.println(s1 + name.substring(1));
导致这些编译错误:
类型不匹配:无法从InputStreamReader转换为BufferedReader
Type mismatch: cannot convert from InputStreamReader to BufferedReader
无法在基本类型char上调用toUppercase()
Cannot invoke toUppercase() on the primitive type char
推荐答案
使用Apache的公共库。从这些东西中释放你的大脑,避免使用Null Pointer&索引超出限制的例外
第1步:
导入apache的常用lang库把它放在 build.gradle
依赖项中
Import apache's common lang library by putting this in build.gradle
dependencies
compile 'org.apache.commons:commons-lang3:3.6'
第2步:
如果您确定您的字符串全部为小写,或者您只需要初始化第一个字母,请直接致电
If you are sure that your string is all lower case, or all you need is to initialize the first letter, directly call
StringUtils.capitalize(yourString);
如果你想确保只有第一个字母大写,就像这样做 enum
,首先调用 toLowerCase()
并记住它会抛出 NullPointerException
如果输入字符串为null。
If you want to make sure that only the first letter is capitalized, like doing this for an enum
, call toLowerCase()
first and keep in mind that it will throw NullPointerException
if the input string is null.
StringUtils.capitalize(YourEnum.STUFF.name().toLowerCase());
StringUtils.capitalize(yourString.toLowerCase());
以下是apache提供的更多示例。它是免费的例外
Here are more samples provided by apache. it's exception free
StringUtils.capitalize(null) = null
StringUtils.capitalize("") = ""
StringUtils.capitalize("cat") = "Cat"
StringUtils.capitalize("cAt") = "CAt"
StringUtils.capitalize("'cat'") = "'cat'"
注意:
WordUtils
也包含在此库中,但已弃用。请不要使用它。
WordUtils
is also included in this library, but is deprecated. Please do not use that.
这篇关于如何在Java中大写字符串的第一个字母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!