[java] First char to upper case

Possible Duplicate:
How to upper case every first letter of word in a string?
Most efficient way to make the first character of a String lower case?

I want to convert the first letter of a string to upper case. I am attempting to use replaceFirst() as described in JavaDocs, but I have no idea what is meant by regular expression.

Here is the code I have tried so far:

public static String cap1stChar(String userIdea)
{
    String betterIdea, userIdeaUC;
    char char1;
    userIdeaUC = userIdea.toUpperCase();
    char1 = userIdeaUC.charAt(0);
    betterIdea = userIdea.replaceFirst(char1); 
    return betterIdea;
}//end cap1stChar

The compiler error is that the argument lists differ in lengths. I presume that is because the regex is missing, however I don't know what that is exactly.

This question is related to java string

The answer is


For completeness, if you wanted to use replaceFirst, try this:

public static String cap1stChar(String userIdea)
{
  String betterIdea = userIdea;
  if (userIdea.length() > 0)
  {
    String first = userIdea.substring(0,1);
    betterIdea = userIdea.replaceFirst(first, first.toUpperCase());
  }
  return betterIdea;
}//end cap1stChar

userIdeaUC = userIdea.substring(0, 1).toUpperCase() + userIdea.length() > 1 ? userIdea.substring(1) : "";

or

userIdeaUC = userIdea.substring(0, 1).toUpperCase();
if(userIdea.length() > 1)
   userIdeaUC += userIdea.substring(1);

Or you can do

s = Character.toUpperCase(s.charAt(0)) + s.substring(1); 

String toCamelCase(String string) {
    StringBuffer sb = new StringBuffer(string);
    sb.replace(0, 1, string.substring(0, 1).toUpperCase());
    return sb.toString();

}

Comilation error is due arguments are not properly provided, replaceFirst accepts regx as initial arg. [a-z]{1} will match string of simple alpha characters of length 1.

Try this.

betterIdea = userIdea.replaceFirst("[a-z]{1}", userIdea.substring(0,1).toUpperCase())

public static String cap1stChar(String userIdea)
{
    char[] stringArray = userIdea.toCharArray();
    stringArray[0] = Character.toUpperCase(stringArray[0]);
    return userIdea = new String(stringArray);
}