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


当前回答

你要做的可能是:

s1 = name.substring(0, 1).toUpperCase() + name.substring(1);

(将第一个字符转换为大写,并添加原始字符串的其余部分)

此外,您创建了一个输入流读取器,但从不读取任何行。因此name将始终为空。

这应该可以工作:

BufferedReader br = new InputstreamReader(System.in);
String name = br.readLine();
String s1 = name.substring(0, 1).toUpperCase() + name.substring(1);

其他回答

为了使输入字符串的第一个字母大写,我们首先在空格上分割字符串,然后使用map提供的集合转换过程

<T, R> Array<out T>.map(

   transform: (T) -> R

): List<R>

要转换,每个分割的字符串首先小写,然后大写第一个字母。这个映射转换将返回一个需要使用joinToString函数将其转换为字符串的列表。

科特林

fun main() {
    
    /*
     * Program that first convert all uper case into lower case then 
     * convert fist letter into uppercase
     */
    
    val str = "aLi AzAZ alam"
    val calStr = str.split(" ").map{it.toLowerCase().capitalize()}
    println(calStr.joinToString(separator = " "))
}

输出

StringUtils.capitalize(..) from commons-lang

当前的答案要么是不正确的,要么是把这个简单的任务过于复杂了。在做了一些研究之后,我想到了以下两种方法:

1. 字符串的substring()方法

public static String capitalize(String str) {
    if(str== null || str.isEmpty()) {
        return str;
    }

    return str.substring(0, 1).toUpperCase() + str.substring(1);
}

例子:

System.out.println(capitalize("java")); // Java
System.out.println(capitalize("beTa")); // BeTa
System.out.println(capitalize(null)); // null

2. Apache Commons Lang

Apache Commons Lang库为此目的提供了StringUtils类:

System.out.println(StringUtils.capitalize("apache commons")); // Apache commons
System.out.println(StringUtils.capitalize("heLLO")); // HeLLO
System.out.println(StringUtils.uncapitalize(null)); // null

不要忘记在pom.xml文件中添加以下依赖项:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.9</version>
</dependency>

这只是为了告诉你,你没有错。

BufferedReader br = new InputstreamReader(System.in);
// Assuming name is not blank
String name = br.readLine(); 

//No more error telling that you cant convert char to string
String s1 = (""+name.charAt(0)).toUppercase());
// Or, as Carlos prefers. See the comments to this post.
String s1 = Character.toString(name.charAt(0)).toUppercase());

System.out.println(s1+name.substring(1));

注意:这根本不是最好的方法。这只是为了告诉OP,它也可以使用charAt()来完成。;)

试试这个,对我很管用。

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