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


当前回答

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

    userName = userName.toLowerCase();

然后把第一个字母大写:

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

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

其他回答

下面的例子也将特殊字符后的单词大写,如[/-]

  public static String capitalize(String text) {
    char[] stringArray = text.trim().toCharArray();
    boolean wordStarted = false;
    for( int i = 0; i < stringArray.length; i++) {
      char ch = stringArray[i];
      if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == '\'') {
        if( !wordStarted ) {
          stringArray[i] = Character.toUpperCase(stringArray[i]);
          wordStarted = true;
        } 
      } else {
        wordStarted = false;
      }
    }
    return new String(stringArray);
  }

Example:
capitalize("that's a beautiful/wonderful life we have.We really-do")

Output:
That's A Beautiful/Wonderful Life We Have.We Really-Do
String str1 = "hello";
str1.substring(0, 1).toUpperCase()+str1.substring(1);

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

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)));

如果你使用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。像其他答案建议的那样大写。

字符串首字母大写的更短/更快的版本代码是:

String name  = "stackoverflow"; 
name = name.substring(0,1).toUpperCase() + name.substring(1).toLowerCase();

name的值为Stackoverflow