我使用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;
}

其他回答

你也可以试试这个:

 String s1 = br.readLine();
 char[] chars = s1.toCharArray();
 chars[0] = Character.toUpperCase(chars[0]);
 s1= new String(chars);
 System.out.println(s1);

这比使用substring更好(优化了)。(但不用担心小弦)

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

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

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

用WordUtils capitalize (str)。

这是我这边的解决方案,所有条件都检查过了。

   import java.util.Objects;

public class CapitalizeFirstCharacter {

    public static void main(String[] args) {

        System.out.println(capitailzeFirstCharacterOfString("jwala")); //supply input string here
    }

    private static String capitailzeFirstCharacterOfString(String strToCapitalize) {

        if (Objects.nonNull(strToCapitalize) && !strToCapitalize.isEmpty()) {
            return strToCapitalize.substring(0, 1).toUpperCase() + strToCapitalize.substring(1);
        } else {
            return "Null or Empty value of string supplied";

        }

    }

}