I want to convert the first character of a string to Uppercase and the rest of the characters to lowercase. How can I do it?
Example:
String inputval="ABCb" OR "a123BC_DET" or "aBcd" String outputval="Abcb" or "A123bc_det" or "Abcd"
charAt(i))) to check the character is lowercase. If True, we used the toUpperCase() ( Character. toUpperCase( StrToToggle. charAt(i)) ) to convert it to the uppercase character.
Java String toLowerCase() Method The toLowerCase() method converts a string to lower case letters. Note: The toUpperCase() method converts a string to upper case letters.
Try this on for size:
String properCase (String inputVal) { // Empty strings should be returned as-is. if (inputVal.length() == 0) return ""; // Strings with only one character uppercased. if (inputVal.length() == 1) return inputVal.toUpperCase(); // Otherwise uppercase first letter, lowercase the rest. return inputVal.substring(0,1).toUpperCase() + inputVal.substring(1).toLowerCase(); }
It basically handles special cases of empty and one-character string first and correctly cases a two-plus-character string otherwise. And, as pointed out in a comment, the one-character special case isn't needed for functionality but I still prefer to be explicit, especially if it results in fewer useless calls, such as substring to get an empty string, lower-casing it, then appending it as well.
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