Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make String first letter capital in java

As of now I'm using this code to make my first letter in a string capital

String output = input.substring(0, 1).toUpperCase() + input.substring(1); 

This seems very dirty to me ..is there any direct or elegant way..

like image 360
Suresh Atta Avatar asked Jun 10 '13 14:06

Suresh Atta


People also ask

How do you capitalize the first letter of a string in Java?

The simplest way to capitalize the first letter of a string in Java is by using the String. substring() method: String str = "hello world!"; // capitalize first letter String output = str. substring(0, 1).

How do you capitalize words in Java?

Java For Testers You can capitalize words in a string using the toUpperCase() method of the String class. This method converts the contents of the current string to Upper case letters.

How do you capitalize first letter?

You should always capitalize the first letter of the first word in a sentence, no matter what the word is. Take, for example, the following sentences: The weather was beautiful. It was sunny all day. Even though the and it aren't proper nouns, they're capitalized here because they're the first words in their sentences.


2 Answers

How about this:

String output = Character.toUpperCase(input.charAt(0)) + input.substring(1); 

I can't think of anything cleaner without using external libraries, but this is definitely better than what you currently have.

like image 79
arshajii Avatar answered Oct 11 '22 08:10

arshajii


You should have a look at StringUtils class from Apache Commons Lang lib - it has method .capitalize()

Description from the lib:

Capitalizes a String changing the first letter to title case as per Character.toTitleCase(char). No other letters are changed.

like image 24
user Avatar answered Oct 11 '22 08:10

user