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


当前回答

再举一个例子,如何让用户输入的第一个字母大写:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String string = br.readLine();
// handle supplementary characters
IntStream.concat(
        IntStream.of(string.codePointAt(0))
                .map(Character::toUpperCase), string.codePoints().skip(1)
)
.forEach(cp -> System.out.print(Character.toChars(cp)));

其他回答

为了避免异常(IndexOutOfBoundsException或NullPointerException当使用子字符串(0,1)为空或空字符串时),您可以使用regex ("^.") (自Java 9起):

    try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
        String name = reader.readLine();

        name = Pattern.compile("^.")    // regex for the first character of a string
                .matcher(name)
                .replaceFirst(matchResult -> matchResult.group().toUpperCase());

        System.out.println(name);
    } catch(IOException ignore) {}

因为您第一次从原始字符串中获得Char。你不能在char上使用String属性,所以先使用to upper,然后使用charAt

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

将字符串设置为小写,然后将第一个字母设置为大写,如下所示:

    userName = userName.toLowerCase();

然后把第一个字母大写:

    userName = userName.substring(0, 1).toUpperCase() + userName.substring(1).toLowerCase();

Substring只是得到一个更大的字符串的一部分,然后我们将它们组合在一起。

谢谢,我已经阅读了一些评论,并带来了以下内容

public static void main(String args[]) 
{
String myName = "nasser";
String newName = myName.toUpperCase().charAt(0) +  myName.substring(1);
System.out.println(newName );
}

我希望它能有所帮助 祝你好运

使用替换方法。

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