且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Java中将字符串的第一个字母大写?

更新时间:2021-11-14 22:28:05

使用 Apache 的公共库.从这些东西中解放你的大脑,避免空指针和索引越界异常

第 1 步:

通过将其放在 build.gradle 依赖项中来导入 apache 的通用 lang 库

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.

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.