我使用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 s1 = br.readLine();
 char[] chars = s1.toCharArray();
 chars[0] = Character.toUpperCase(chars[0]);
 s1= new String(chars);
 System.out.println(s1);

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

其他回答

import java.util.*;
public class Program
{
    public static void main(String[] args) 
      {
        Scanner sc=new Scanner(System.in);
        String s1=sc.nextLine();
        String[] s2=s1.split(" ");//***split text into words***
        ArrayList<String> l = new ArrayList<String>();//***list***
        for(String w: s2)
        l.add(w.substring(0,1).toUpperCase()+w.substring(1)); 
        //***converting 1st letter to capital and adding to list***
        StringBuilder sb = new StringBuilder();//***i used StringBuilder to convert words to text*** 
        for (String s : l)
          {
             sb.append(s);
             sb.append(" ");
          }
      System.out.println(sb.toString());//***to print output***
      }
}

我已经使用split函数将字符串分割成单词,然后我再次使用list来获得该单词的第一个字母大写,然后我使用字符串生成器以字符串格式打印输出,其中包含空格

String s = "first second third fourth";

        int j = 0;
        for (int i = 0; i < s.length(); i++) {

            if ((s.substring(j, i).endsWith(" "))) {

                String s2 = s.substring(j, i);
                System.out.println(Character.toUpperCase(s.charAt(j))+s2.substring(1));
                j = i;
            }
        }
        System.out.println(Character.toUpperCase(s.charAt(j))+s.substring(j+1));

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

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

使用替换方法。

String newWord = word.replace(String.valueOf(word.charAt(0)), String.valueOf(word.charAt(0)).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
}