How can I capitalize the first letter of each word

2019-01-25 02:12发布

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

10条回答
欢心
2楼-- · 2019-01-25 02:54
$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".

查看更多
戒情不戒烟
3楼-- · 2019-01-25 02:55

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.

查看更多
疯言疯语
4楼-- · 2019-01-25 02:57

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

查看更多
\"骚年 ilove
5楼-- · 2019-01-25 02:58

This capitalizes only the first word of each line:

perl -ne "print (ucfirst($1)$2)  if s/^(\w)(.*)/\1\2/" file
查看更多
地球回转人心会变
6楼-- · 2019-01-25 03:07
$string =~ s/(\w+)/\u$1/g;

should work just fine

查看更多
Ridiculous、
7楼-- · 2019-01-25 03:09

Take a look at the ucfirst function.

$line = join " ", map {ucfirst} split " ", $line;
查看更多
登录 后发表回答