我使用Java从用户获得一个字符串输入。我试着让输入的第一个字母大写。

我试了一下:

String name;

BufferedReader br = new InputStreamReader(System.in);

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

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

这导致了以下编译错误:

类型不匹配:不能从InputStreamReader转换为BufferedReader 不能在基本类型char上调用toUppercase()


当前回答

以下是我关于Android中所有可能的选项的详细文章

Java中字符串首字母大写的方法

public static String capitalizeString(String str) {
        String retStr = str;
        try { // We can face index out of bound exception if the string is null
            retStr = str.substring(0, 1).toUpperCase() + str.substring(1);
        }catch (Exception e){}
        return retStr;
}

在KOTLIN中首字母大写的方法

fun capitalizeString(str: String): String {
        var retStr = str
        try { // We can face index out of bound exception if the string is null
            retStr = str.substring(0, 1).toUpperCase() + str.substring(1)
        } catch (e: Exception) {
        }
        return retStr
}

其他回答

使用替换方法。

String newWord = word.replace(String.valueOf(word.charAt(0)), String.valueOf(word.charAt(0)).toUpperCase());

StringUtils.capitalize(..) from commons-lang

你也可以试试这个:

 String s1 = br.readLine();
 char[] chars = s1.toCharArray();
 chars[0] = Character.toUpperCase(chars[0]);
 s1= new String(chars);
 System.out.println(s1);

这比使用substring更好(优化了)。(但不用担心小弦)

使用Apache的公共库。把你的大脑从这些东西中解放出来,避免空指针和索引脱离绑定异常

步骤1:

在build中导入apache的common lang库。gradle依赖性

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

步骤2:

如果你确定你的字符串都是小写的,或者你只需要初始化第一个字母,直接调用

StringUtils.capitalize(yourString);

如果你想确保只有第一个字母是大写的,就像在枚举中那样,首先调用toLowerCase(),并记住,如果输入字符串为空,它将抛出NullPointerException。

StringUtils.capitalize(YourEnum.STUFF.name().toLowerCase());
StringUtils.capitalize(yourString.toLowerCase());

以下是apache提供的更多示例。它是无异常的

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

注意:

WordUtils也包含在这个库中,但已弃用。请不要用这个。

试试这个

这个方法做的是,考虑单词“hello world”这个方法把它变成“hello world”每个单词的开头大写。

 private String capitalizer(String word){

        String[] words = word.split(" ");
        StringBuilder sb = new StringBuilder();
        if (words[0].length() > 0) {
            sb.append(Character.toUpperCase(words[0].charAt(0)) + words[0].subSequence(1, words[0].length()).toString().toLowerCase());
            for (int i = 1; i < words.length; i++) {
                sb.append(" ");
                sb.append(Character.toUpperCase(words[i].charAt(0)) + words[i].subSequence(1, words[i].length()).toString().toLowerCase());
            }
        }
        return  sb.toString();

    }