如何在Java中将字符串的第一个字母大写? [英] How to capitalize the first letter of a String in Java?

查看:36
本文介绍了如何在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 的公共库.从这些东西中解放你的大脑,避免空指针和索引越界异常

    第 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.

    这篇关于如何在Java中将字符串的第一个字母大写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆