Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capitalize the first character of each word in a string

Is there a function built into Java that capitalizes the first character of each word in a String, and does not affect the others?

Examples:

  • jon skeet -> Jon Skeet
  • miles o'Brien -> Miles O'Brien (B remains capital, this rules out Title Case)
  • old mcdonald -> Old Mcdonald*

*(Old McDonald would be find too, but I don't expect it to be THAT smart.)

A quick look at the Java String Documentation reveals only toUpperCase() and toLowerCase(), which of course do not provide the desired behavior. Naturally, Google results are dominated by those two functions. It seems like a wheel that must have been invented already, so it couldn't hurt to ask so I can use it in the future.

like image 990
WillfulWizard Avatar asked Dec 12 '09 08:12

WillfulWizard


People also ask

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

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 capitalize the first letter of words in word?

To use a keyboard shortcut to change between lowercase, UPPERCASE, and Capitalize Each Word, select the text and press SHIFT + F3 until the case you want is applied.

Which function capitalize the first character of a string?

string capitalize() in Python In Python, the capitalize() method returns a copy of the original string and converts the first character of the string to a capital (uppercase) letter while making all other characters in the string lowercase letters.


1 Answers

WordUtils.capitalize(str) (from apache commons-text)

(Note: if you need "fOO BAr" to become "Foo Bar", then use capitalizeFully(..) instead)

like image 184
Bozho Avatar answered Sep 20 '22 14:09

Bozho