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


当前回答

以下是我关于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
}

其他回答

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

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

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

您可以使用以下代码:

public static String capitalizeString(String string) {

    if (string == null || string.trim().isEmpty()) {
        return string;
    }
    char c[] = string.trim().toLowerCase().toCharArray();
    c[0] = Character.toUpperCase(c[0]);

    return new String(c);

}

使用JUnit的示例测试:

@Test
public void capitalizeStringUpperCaseTest() {

    String string = "HELLO WORLD  ";

    string = capitalizeString(string);

    assertThat(string, is("Hello world"));
}

@Test
public void capitalizeStringLowerCaseTest() {

    String string = "hello world  ";

    string = capitalizeString(string);

    assertThat(string, is("Hello world"));
}

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

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

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

一种方法。

String input = "someТекст$T%$4čřЭ"; //Enter your text.
if (input == null || input.isEmpty()) {
    return "";
}

char [] chars = input.toCharArray();
chars[0] = chars[0].toUpperCase();
String res = new String(chars);
return res;

此方法的缺点是,如果inputString很长,则将有三个这样长度的对象。和你一样

String s1 = input.substring(1).toUpperCase();
String s2 = input.substring(1, lenght);
String res = s1 + s2;

甚至

//check if not null.
StringBuilder buf = new StringBuilder(input);
char ch = buf.getCharAt(0).toUpperCase();
buf.setCharAt(0, ch);
return buf.toString();