我使用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 capitaliseName(String name) {
    String collect[] = name.split(" ");
    String returnName = "";
    for (int i = 0; i < collect.length; i++) {
        collect[i] = collect[i].trim().toLowerCase();
        if (collect[i].isEmpty() == false) {
            returnName = returnName + collect[i].substring(0, 1).toUpperCase() + collect[i].substring(1) + " ";
        }
    }
    return returnName.trim();
}

usase: capitaliseName(“saurav khan”); 输出:Saurav Khan

其他回答

如果你使用SPRING:

import static org.springframework.util.StringUtils.capitalize;
...


    return capitalize(name);

实现:org/springframework/util/StringUtils.java # L535-L555

裁判:javadoc api / org/springframework/util/StringUtils.html #大写


注意:如果你已经有Apache Common Lang依赖,那么考虑使用它们的StringUtils。像其他答案建议的那样大写。

用WordUtils capitalize (str)。

字符字符不能存储在字符串中。 char和String不能连接。 String. valueof()用于将char转换为String

输入

india

Code

String name = "india";
char s1 = name.charAt(0).toUppercase()); // output: 'I'
System.out.println(String.valueOf(s1) + name.substring(1)); // output: "I"+ "ndia";

输出

India

试试这个

这个方法做的是,考虑单词“hello world”这个方法把它变成“hello world”每个单词的开头大写。

 private String capitalizer(String word){

        String[] words = word.split(" ");
        StringBuilder sb = new StringBuilder();
        if (words[0].length() > 0) {
            sb.append(Character.toUpperCase(words[0].charAt(0)) + words[0].subSequence(1, words[0].length()).toString().toLowerCase());
            for (int i = 1; i < words.length; i++) {
                sb.append(" ");
                sb.append(Character.toUpperCase(words[i].charAt(0)) + words[i].subSequence(1, words[i].length()).toString().toLowerCase());
            }
        }
        return  sb.toString();

    }
class CapitalizeWords
{
    public static void main(String[] args) 
    {
        String input ="welcome to kashmiri geeks...";

        System.out.println(input);

        String[] str = input.split(" ");

        for(int i=0; i< str.length; i++)
        {
            str[i] = (str[i]).substring(0,1).toUpperCase() + (str[i]).substring(1);
        }

        for(int i=0;i<str.length;i++)
        {
            System.out.print(str[i]+" ");
        }


    }
}