我使用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()


当前回答

只是重做了Jorgesys代码,并添加了一些检查,因为很少有与字符串长度相关的情况。不要做空参考检查在我的情况下。

 public static String capitalizeFirstLetter(@NonNull String customText){
        int count = customText.length();
        if (count == 0) {
            return customText;
        }
        if (count == 1) {
            return customText.toUpperCase();
        }
        return customText.substring(0, 1).toUpperCase() + customText.substring(1).toLowerCase();
    }

其他回答

看一下ACL WordUtils。

WordUtils。大写("your string") == "your string"

如何大写单词的第一个字母在一个字符串?

如果你使用SPRING:

import static org.springframework.util.StringUtils.capitalize;
...


    return capitalize(name);

实现:org/springframework/util/StringUtils.java # L535-L555

裁判:javadoc api / org/springframework/util/StringUtils.html #大写


注意:如果你已经有Apache Common Lang依赖,那么考虑使用它们的StringUtils。像其他答案建议的那样大写。

用WordUtils capitalize (str)。

System.out.println(Character.toString(A.charAt(0)).toUpperCase()+A.substring(1));

P.S = a是一个字符串。

你可以使用子字符串进行简单的hack;)。

String name;
    
String s1 = name.substring(0, 1).toUpperCase() + name.substring(1, name.length());

System.out.println(s1));