Question

What is the easiest way to capitalize the first letter in each word of a string?

Was it helpful?

Solution

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.

OTHER TIPS

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

or Text::Autoformat

Take a look at the ucfirst function.

$line = join " ", map {ucfirst} split " ", $line;
$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".

$string =~ s/(\w+)/\u$1/g;

should work just fine

This capitalizes only the first word of each line:

perl -ne "print (ucfirst($1)$2)  if s/^(\w)(.*)/\1\2/" file

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.

You can use 'Title Case', its a very cool piece of code written in Perl.

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.

try this :

echo "what's the wrong answer?" |perl -pe 's/^/ /; s/\s(\w+)/ \u$1/g; s/^ //'

What's The Wrong Answer?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top