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


当前回答

试试这个,对我很管用。

public static String capitalizeName(String name) {
    String fullName = "";
    String names[] = name.split(" ");
    for (String n: names) {
        fullName = fullName + n.substring(0, 1).toUpperCase() + n.toLowerCase().substring(1, n.length()) + " ";
    }
    return fullName;
}

其他回答

这只是为了告诉你,你没有错。

BufferedReader br = new InputstreamReader(System.in);
// Assuming name is not blank
String name = br.readLine(); 

//No more error telling that you cant convert char to string
String s1 = (""+name.charAt(0)).toUppercase());
// Or, as Carlos prefers. See the comments to this post.
String s1 = Character.toString(name.charAt(0)).toUppercase());

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

注意:这根本不是最好的方法。这只是为了告诉OP,它也可以使用charAt()来完成。;)

只是重做了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();
    }

您可以使用substring()来做到这一点。

但有两种情况:

案例1

如果你要大写的字符串是人类可读的,你还应该指定默认的语言环境:

String firstLetterCapitalized = 
    myString.substring(0, 1).toUpperCase(Locale.getDefault()) + myString.substring(1);

案例2

如果要大写的字符串是机器可读的,请避免使用locale . getdefault(),因为返回的字符串在不同的地区不一致,在这种情况下总是指定相同的地区(例如,toUpperCase(locale . english))。这将确保用于内部处理的字符串是一致的,这将帮助您避免难以发现的错误。

注意:您不必为toLowerCase()指定Locale.getDefault(),因为这是自动完成的。

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

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

System.out.println(s1));

用WordUtils capitalize (str)。