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


当前回答

你可以使用类WordUtils。

假设你的字符串是“当前地址”,然后使用

* * * *强烈textWordutils.capitaliz(字符串); 输出:当前地址

参见:http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/WordUtils.html

其他回答

String str1 = "hello";
str1.substring(0, 1).toUpperCase()+str1.substring(1);

因为您第一次从原始字符串中获得Char。你不能在char上使用String属性,所以先使用to upper,然后使用charAt

String s1 = name.toUppercase().charAt(0);

谢谢,我已经阅读了一些评论,并带来了以下内容

public static void main(String args[]) 
{
String myName = "nasser";
String newName = myName.toUpperCase().charAt(0) +  myName.substring(1);
System.out.println(newName );
}

我希望它能有所帮助 祝你好运

要将字符串中每个单词的第一个字符大写,

首先,你需要获得该字符串的每个单词&对于这个分裂字符串,其中任何空间都存在,使用split方法如下所示,并将每个单词存储在一个数组中。 然后创建一个空字符串。之后,使用substring()方法获取对应单词的第一个字符和剩余字符,并将它们存储在两个不同的变量中。

然后使用toUpperCase()方法将第一个字符大写,并将如下所示的其余字符添加到空字符串中。

public class Test {  
     public static void main(String[] args)
     {
         String str= "my name is khan";        // string
         String words[]=str.split("\\s");      // split each words of above string
         String capitalizedWord = "";         // create an empty string

         for(String w:words)
         {  
              String first = w.substring(0,1);    // get first character of each word
              String f_after = w.substring(1);    // get remaining character of corresponding word
              capitalizedWord += first.toUpperCase() + f_after+ " ";  // capitalize first character and add the remaining to the empty string and continue
         }
         System.out.println(capitalizedWord);    // print the result
     }
}
public static String capitalizer(final String texto) {

    // split words
    String[] palavras = texto.split(" ");
    StringBuilder sb = new StringBuilder();

    // list of word exceptions
    List<String> excessoes = new ArrayList<String>(Arrays.asList("de", "da", "das", "do", "dos", "na", "nas", "no", "nos", "a", "e", "o", "em", "com"));

    for (String palavra : palavras) {

        if (excessoes.contains(palavra.toLowerCase()))
            sb.append(palavra.toLowerCase()).append(" ");
        else
            sb.append(Character.toUpperCase(palavra.charAt(0))).append(palavra.substring(1).toLowerCase()).append(" ");
    }
    return sb.toString().trim();
}