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


当前回答

使用此实用程序方法将每个单词的第一个字母大写。

String capitalizeAllFirstLetters(String name) 
{
    char[] array = name.toCharArray();
    array[0] = Character.toUpperCase(array[0]);
 
    for (int i = 1; i < array.length; i++) {
        if (Character.isWhitespace(array[i - 1])) {
            array[i] = Character.toUpperCase(array[i]);
        }
    }
 
    return new String(array);
}

其他回答

为了避免异常(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) {}

来自Apache Commons的wordutil .capitalize(java.lang.String)。

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

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

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

你可以试试这个

/**
 * capitilizeFirst(null)  -> ""
 * capitilizeFirst("")    -> ""
 * capitilizeFirst("   ") -> ""
 * capitilizeFirst(" df") -> "Df"
 * capitilizeFirst("AS")  -> "As"
 *
 * @param str input string
 * @return String with the first letter capitalized
 */
public String capitilizeFirst(String str)
{
    // assumptions that input parameter is not null is legal, as we use this function in map chain
    Function<String, String> capFirst = (String s) -> {
        String result = ""; // <-- accumulator

        try { result += s.substring(0, 1).toUpperCase(); }
        catch (Throwable e) {}
        try { result += s.substring(1).toLowerCase(); }
        catch (Throwable e) {}

        return result;
    };

    return Optional.ofNullable(str)
            .map(String::trim)
            .map(capFirst)
            .orElse("");
}

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

  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