79

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"

6 Answers 6

117

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.

4
  • This has an unneeded case. See my answer. Nov 15, 2015 at 22:02
  • 1
    @espertus, you should post your answer before asking people to look at it, otherwise you're likely to drive them insane :-)
    – paxdiablo
    Nov 15, 2015 at 22:08
  • Sorry, @paxdiablo. Thanks for the smiley. :-) Nov 16, 2015 at 2:25
  • Do you mean more insane than someone waiting to see how someone with 200 times their reputation is going to respond to a relative n00b claiming to have a better answer? ;-) Nov 16, 2015 at 2:33
20
String a = "ABCD"

using this

a.toLowerCase();

all letters will convert to simple, "abcd"
using this

a.toUpperCase()

all letters will convert to Capital, "ABCD"

this conver first letter to capital:

a.substring(0,1).toUpperCase()

this conver other letter Simple

a.substring(1).toLowerCase();

we can get sum of these two

a.substring(0,1).toUpperCase() + a.substring(1).toLowerCase();

result = "Abcd"

11

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

0
8
String inputval="ABCb";
String result = inputval.substring(0,1).toUpperCase() + inputval.substring(1).toLowerCase();

Would change "ABCb" to "Abcb"

1
  • 7
    Don't forget to handle if inputval is 0 or 1 length.
    – Steve Kuo
    Mar 3, 2010 at 23:07
5

I consider this simpler than any prior correct answer. I'll also throw in javadoc. :-)

/**
 * Converts the given string to title case, where the first
 * letter is capitalized and the rest of the string is in
 * lower case.
 * 
 * @param s a string with unknown capitalization
 * @return a title-case version of the string
 */
public static String toTitleCase(String s)
{
    if (s.isEmpty())
    {
        return s;
    }
    return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
}

Strings of length 1 do not needed to be treated as a special case because s.substring(1) returns the empty string when s has length 1.

2
  • 2
    Paxdiablo's version avoids unnecessary concatenations when s.length is 1. This version has fewer lines of code, but it is debatable whether it is "simpler". In general, more concise doesn't imply more readable. Performance ... difficulty to say, not least because it depends on the probability of one-character strings.
    – Stephen C
    Nov 15, 2015 at 22:28
  • 1
    @StephenC Fair enough. Nov 16, 2015 at 2:27
-5
/* This code is just for convert a single uppercase character to lowercase 
character & vice versa.................*/

/* This code is made without java library function, and also uses run time input...*/



import java.util.Scanner;

class CaseConvert {
char c;
void input(){
//@SuppressWarnings("resource")  //only eclipse users..
Scanner in =new Scanner(System.in);  //for Run time input
System.out.print("\n Enter Any Character :");
c=in.next().charAt(0);     // input a single character
}
void convert(){
if(c>=65 && c<=90){
    c=(char) (c+32);
    System.out.print("Converted to Lowercase :"+c);
}
else if(c>=97&&c<=122){
        c=(char) (c-32);
        System.out.print("Converted to Uppercase :"+c);
}
else
    System.out.println("invalid Character Entered  :" +c);

}


  public static void main(String[] args) {
    // TODO Auto-generated method stub
    CaseConvert obj=new CaseConvert();
    obj.input();
    obj.convert();
    }

}



/*OUTPUT..Enter Any Character :A Converted to Lowercase :a 
Enter Any Character :a Converted to Uppercase :A
Enter Any Character :+invalid Character Entered  :+*/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.