問題:在Java中,如何使一個字符串的首字母變為大寫
我使用Java去獲取用戶的字符串輸入。我嘗試使他們輸入的第一個字符大寫
我嘗試這樣:
String name;BufferedReader br = new InputStreamReader(System.in);String s1 = name.charAt(0).toUppercase());System.out.println(s1 + name.substring(1));
導致了編譯錯誤
Type mismatch: cannot convert from InputStreamReader to BufferedReader
Cannot invoke toUppercase() on the primitive type char
回答一
String str = "java";
String cap = str.substring(0, 1).toUpperCase() + str.substring(1);
// cap = "Java"
在你的例子中
public static void main(String[] args) throws IOException {BufferedReader br = new BufferedReader(new InputStreamReader(System.in));// Actually use the ReaderString name = br.readLine();// Don't mistake String object with a Character objectString s1 = name.substring(0, 1).toUpperCase();String nameCapitalized = s1 + name.substring(1);System.out.println(nameCapitalized);
}
回答二
使用 Apache的工具庫。把你的大腦從這些事情里解放出來并且避免空指針和數組越界
步驟 1:
通過把這個放進去build.gradle的依賴理,來導入apache's common lang library
compile 'org.apache.commons:commons-lang3:3.6'
步驟 2:
如果你確定你的字符串都是小寫的,或者你需要初始化所有的首字符,直接這樣調用
StringUtils.capitalize(yourString);
如果你想要確保只有首字母是大寫的,像這樣做一個枚舉,調用首先調用toLowerCase()
,但是記住如果你輸入的是空字符串,他會報空指針異常
StringUtils.capitalize(YourEnum.STUFF.name().toLowerCase());
StringUtils.capitalize(yourString.toLowerCase());
Here are more samples provided by apache. it's exception free
這里有一些apache提供的例子,是沒有異常的。
StringUtils.capitalize(null) = null
StringUtils.capitalize("") = ""
StringUtils.capitalize("cat") = "Cat"
StringUtils.capitalize("cAt") = "CAt"
StringUtils.capitalize("'cat'") = "'cat'"
注意
WordUtils 也包含在這個庫里面, 但是已經過時了,就不要再使用了.
文章翻譯自Stack Overflow:https://stackoverflow.com/questions/3904579/how-to-capitalize-the-first-letter-of-a-string-in-java