我使用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 capitalizeAllFirstLetters(String name) 
{
    char[] array = name.toCharArray();
    array[0] = Character.toUpperCase(array[0]);
 
    for (int i = 1; i < array.length; i++) {
        if (Character.isWhitespace(array[i - 1])) {
            array[i] = Character.toUpperCase(array[i]);
        }
    }
 
    return new String(array);
}

其他回答

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

首先,你需要获得该字符串的每个单词&对于这个分裂字符串,其中任何空间都存在,使用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
     }
}
System.out.println(Character.toString(A.charAt(0)).toUpperCase()+A.substring(1));

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

其中一个答案的正确率是95%,但它在我的unitTest中失败了@Ameen Maheen的解决方案几乎完美。除了在输入被转换为String数组之前,您必须修剪输入。所以最完美的一个:

private String convertStringToName(String name) {
        name = name.trim();
        String[] words = name.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();
    }

为了使输入字符串的第一个字母大写,我们首先在空格上分割字符串,然后使用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 = " "))
}

输出

用WordUtils capitalize (str)。