What is the easiest way to capitalize the first letter in each word of a string?
views:
5400answers:
9Take a look at the ucfirst function.
$line = join " ", map {ucfirst} split " ", $line;
See the faq.
I don't believe ucfirst() satisfies the OP's question to capitalize the first letter of each word in a string without splitting the string and joining it later.
Note that the FAQ solution doesn't work if you have words that are in all-caps and you want them to be (only) capitalized instead. You can either make a more complicated regex, or just do a lc on the string before applying the FAQ solution.
The ucfirst function in a map certainly does this, but only in a very rudimentary way. If you want something a bit more sophisticated, have a look at John Gruber's TitleCase script.
As @brian is mentioning in the comments the currently accepted answer by @piCookie is wrong!
$_="what's the wrong answer?";
s/\b(\w)/\U$1/g
print;
This will print "What'S The Wrong Answer?" notice the wrongly capitalized S
As the FAQ says you are probably better off using
s/([\w']+)/\u\L$1/g
$capitalized = join '', map { ucfirst lc } split /(\s+)/, $line;
By capturing the whitespace, it is inserted in the list and used to rebuild the original spacing. "ucfirst lc" capitalizes "teXT" to "Text".
You can use 'Title Case', its a very cool piece of code written in PERL.
see here related script of Capitalize Words
http://java.pakcarid.com/Cpp.aspx?sub=366&ff=2954&topid=34&sls=25