Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting to upper and lower case in Java

Tags:

java

string

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" 
like image 944
Arav Avatar asked Mar 03 '10 22:03

Arav


People also ask

How do you toggle uppercase and lowercase in Java?

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.

How do you convert to lowercase in Java?

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.


1 Answers

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.

like image 80
paxdiablo Avatar answered Oct 02 '22 17:10

paxdiablo