How can I capitalize the first letter of each word in a string in Perl?

若如初见. 提交于 2019-11-30 07:48:00

问题


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


回答1:


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.




回答2:


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




回答3:


Take a look at the ucfirst function.

$line = join " ", map {ucfirst} split " ", $line;



回答4:


$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".




回答5:


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

should work just fine




回答6:


This capitalizes only the first word of each line:

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



回答7:


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.




回答8:


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




回答9:


try this :

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

Output will be:

What's The Wrong Answer?



回答10:


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.



来源:https://stackoverflow.com/questions/77226/how-can-i-capitalize-the-first-letter-of-each-word-in-a-string-in-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!