How to capitalize the first letter of word in a string using Java?
Example strings
one thousand only
two hundred
twenty
seven
How do I change the first character of a string in capital letter and not change the case of any of the other letters?
After the change it should be:
One thousand only
Two hundred
Twenty
Seven
Note: I don't want to use the apache.commons.lang.WordUtils to do this.
Solution 1:
If you only want to capitalize the first letter of a string named input
and leave the rest alone:
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
Now output
will have what you want. Check that your input
is at least one character long before using this, otherwise you'll get an exception.
Solution 2:
public String capitalizeFirstLetter(String original) {
if (original == null || original.length() == 0) {
return original;
}
return original.substring(0, 1).toUpperCase() + original.substring(1);
}
Just... a complete solution, I see it kind of just ended up combining what everyone else ended up posting =P.