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


当前回答

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

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

        }

    }

}

其他回答

以下是我关于Android中所有可能的选项的详细文章

Java中字符串首字母大写的方法

public static String capitalizeString(String str) {
        String retStr = str;
        try { // We can face index out of bound exception if the string is null
            retStr = str.substring(0, 1).toUpperCase() + str.substring(1);
        }catch (Exception e){}
        return retStr;
}

在KOTLIN中首字母大写的方法

fun capitalizeString(str: String): String {
        var retStr = str
        try { // We can face index out of bound exception if the string is null
            retStr = str.substring(0, 1).toUpperCase() + str.substring(1)
        } catch (e: Exception) {
        }
        return retStr
}

给出的答案是只大写一个单词的第一个字母。使用以下代码将整个字符串大写。

public static void main(String[] args) {
    String str = "this is a random string";
    StringBuilder capitalizedString = new StringBuilder();
    String[] splited = str.trim().split("\\s+");

    for (String string : splited) {         
        String s1 = string.substring(0, 1).toUpperCase();
        String nameCapitalized = s1 + string.substring(1);

        capitalizedString.append(nameCapitalized);
        capitalizedString.append(" ");
    }
    System.out.println(capitalizedString.toString().trim());
}

输出: 这是一个随机字符串

使用Apache的公共库。把你的大脑从这些东西中解放出来,避免空指针和索引脱离绑定异常

步骤1:

在build中导入apache的common lang库。gradle依赖性

implementation 'org.apache.commons:commons-lang3:3.6'

步骤2:

如果你确定你的字符串都是小写的,或者你只需要初始化第一个字母,直接调用

StringUtils.capitalize(yourString);

如果你想确保只有第一个字母是大写的,就像在枚举中那样,首先调用toLowerCase(),并记住,如果输入字符串为空,它将抛出NullPointerException。

StringUtils.capitalize(YourEnum.STUFF.name().toLowerCase());
StringUtils.capitalize(yourString.toLowerCase());

以下是apache提供的更多示例。它是无异常的

StringUtils.capitalize(null)  = null
StringUtils.capitalize("")    = ""
StringUtils.capitalize("cat") = "Cat"
StringUtils.capitalize("cAt") = "CAt"
StringUtils.capitalize("'cat'") = "'cat'"

注意:

WordUtils也包含在这个库中,但已弃用。请不要用这个。

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

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

name的值为Stackoverflow

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

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