views:

201

answers:

4

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"
+1  A: 
String inputval="ABCb";
String result = inputval.substring(0,1).toUpperCase() + inputval.substring(1).toLowerCase();

Would change "ABCb" to "Abcb"

Strawberry
Don't forget to handle if inputval is 0 or 1 length.
Steve Kuo
Thanks a lot for the info
Arav
+1  A: 

See this and that question for the solution.

Li0liQ
Thanks a lot for the info
Arav
A: 

WordUtils.capitalizeFully(str) from apache commons-lang has the exact semantics as required.

Bozho
Thanks a lot for the info
Arav
+2  A: 

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();
}
paxdiablo
Thanks a lot for the solution
Arav
Thanks a lot for the solution
Arav