As of now I'm using this code to make my first letter in a string capital
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
This seems very dirty to me ..is there any direct or elegant way..
The simplest way to capitalize the first letter of a string in Java is by using the String. substring() method: String str = "hello world!"; // capitalize first letter String output = str. substring(0, 1).
Java For Testers You can capitalize words in a string using the toUpperCase() method of the String class. This method converts the contents of the current string to Upper case letters.
You should always capitalize the first letter of the first word in a sentence, no matter what the word is. Take, for example, the following sentences: The weather was beautiful. It was sunny all day. Even though the and it aren't proper nouns, they're capitalized here because they're the first words in their sentences.
How about this:
String output = Character.toUpperCase(input.charAt(0)) + input.substring(1);
I can't think of anything cleaner without using external libraries, but this is definitely better than what you currently have.
You should have a look at StringUtils
class from Apache Commons Lang lib - it has method .capitalize()
Description from the lib:
Capitalizes a String changing the first letter to title case as per Character.toTitleCase(char). No other letters are changed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With