Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First char to upper case [duplicate]

Tags:

java

string

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.

like image 642
Matt B Avatar asked Jul 13 '12 05:07

Matt B


People also ask

How do you make first char uppercase?

To capitalize the first character of a string, We can use the charAt() to separate the first character and then use the toUpperCase() function to capitalize it.

How do you create a character in a string uppercase?

toUpperCase(char ch) converts the character argument to uppercase using case mapping information from the UnicodeData file.

Is C sharp capitalize First letter?

In C#, the Toupper() function of the char class converts a character into uppercase. In the case that we will be discussing, only the first character of the string needs to be converted to uppercase; the rest of the string will stay as it is.

Which case capitalizes the first character of every word in the sentence?

Title Case All words are capitalized, except non-initial articles like “a, the, and”, etc. Used for…um, titles. lowercase All letters in all words are lowercase.


2 Answers

Regular Expressions (abbreviated "regex" or "reg-ex") is a string that defines a search pattern.

What replaceFirst() does is it uses the regular expression provided in the parameters and replaces the first result from the search with whatever you pass in as the other parameter.

What you want to do is convert the string to an array using the String class' charAt() method, and then use Character.toUpperCase() to change the character to upper case (obviously). Your code would look like this:

char first = Character.toUpperCase(userIdea.charAt(0)); betterIdea = first + userIdea.substring(1); 

Or, if you feel comfortable with more complex, one-lined java code:

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

Both of these do the same thing, which is converting the first character of userIdea to an upper case character.

like image 74
Jon Egeland Avatar answered Oct 03 '22 02:10

Jon Egeland


Or you can do

s = Character.toUpperCase(s.charAt(0)) + s.substring(1);  
like image 39
Peter Lawrey Avatar answered Oct 03 '22 01:10

Peter Lawrey