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条回答
Fickle 薄情
2楼-- · 2019-01-25 03:10

try this :

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

What's The Wrong Answer?

查看更多
Explosion°爆炸
3楼-- · 2019-01-25 03:16

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

查看更多
家丑人穷心不美
4楼-- · 2019-01-25 03:17

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.

查看更多
劳资没心,怎么记你
5楼-- · 2019-01-25 03:18

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.

查看更多
登录 后发表回答