在Java中,如何使一个字符串的首字母变为大写| Java Debug 笔记

367 阅读1分钟

本文正在参加「Java主题月 - Java Debug笔记活动」,详情查看 活动链接

问题:在Java中,如何使一个字符串的首字母变为大写

我使用Java去获取用户的字符串输入。我尝试使他们输入的第一个字符大写

我尝试这样:

String name;

BufferedReader br = new InputStreamReader(System.in);

String s1 = name.charAt(0).toUppercase());

System.out.println(s1 + name.substring(1));

导致了编译错误

Type mismatch: cannot convert from InputStreamReader to BufferedReader

Cannot invoke toUppercase() on the primitive type char

回答一

String str = "java";
String cap = str.substring(0, 1).toUpperCase() + str.substring(1);
// cap = "Java"

在你的例子中

public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    // Actually use the Reader
    String name = br.readLine();
    // Don't mistake String object with a Character object
    String s1 = name.substring(0, 1).toUpperCase();
    String nameCapitalized = s1 + name.substring(1);
    System.out.println(nameCapitalized);
}

回答二

使用 Apache的工具库。把你的大脑从这些事情里解放出来并且避免空指针和数组越界

步骤 1:

通过把这个放进去build.gradle的依赖理,来导入apache's common lang library

compile 'org.apache.commons:commons-lang3:3.6'

步骤 2:

如果你确定你的字符串都是小写的,或者你需要初始化所有的首字符,直接这样调用

StringUtils.capitalize(yourString);

如果你想要确保只有首字母是大写的,像这样做一个枚举,调用首先调用toLowerCase() ,但是记住如果你输入的是空字符串,他会报空指针异常

StringUtils.capitalize(YourEnum.STUFF.name().toLowerCase());
StringUtils.capitalize(yourString.toLowerCase());
Here are more samples provided by apache. it's exception free

这里有一些apache提供的例子,是没有异常的。

StringUtils.capitalize(null)  = null
StringUtils.capitalize("")    = ""
StringUtils.capitalize("cat") = "Cat"
StringUtils.capitalize("cAt") = "CAt"
StringUtils.capitalize("'cat'") = "'cat'"

注意

WordUtils 也包含在这个库里面, 但是已经过时了,就不要再使用了.

文章翻译自Stack Overflow:stackoverflow.com/questions/3…