如何大写字符串中每个单词的第一个字符 [英] How to capitalize the first character of each word in a string

查看:171
本文介绍了如何大写字符串中每个单词的第一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个内置于Java中的函数可以将字符串中每个单词的第一个字符大写,并且不会影响其他字符?

Is there a function built into Java that capitalizes the first character of each word in a String, and does not affect the others?

示例:


  • jon skeet - > Jon Skeet

  • miles o'Brien - > Miles O'Brien (B仍然存在资本,这排除标题案例)

  • 旧麦克唐纳 - > 旧麦当劳 *

  • jon skeet -> Jon Skeet
  • miles o'Brien -> Miles O'Brien (B remains capital, this rules out Title Case)
  • old mcdonald -> Old Mcdonald*

*( Old McDonald 也会找到,但我不喜欢不要期望它那么聪明。)

*(Old McDonald would be find too, but I don't expect it to be THAT smart.)

快速浏览 Java字符串文档仅显示 toUpperCase() toLowerCase(),这当然不能提供所需的行为。当然,谷歌的结果由这两个功能主导。它看起来像一个必须已经发明的轮子,所以它可以毫无伤害,所以我可以在将来使用它。

A quick look at the Java String Documentation reveals only toUpperCase() and toLowerCase(), which of course do not provide the desired behavior. Naturally, Google results are dominated by those two functions. It seems like a wheel that must have been invented already, so it couldn't hurt to ask so I can use it in the future.

推荐答案

WordUtils.capitalize(str) (来自 apache commons-text

(注:如果您需要fOO BAr成为Foo Bar,请使用 capitalizeFully( ..)代替)

(Note: if you need "fOO BAr" to become "Foo Bar", then use capitalizeFully(..) instead)

这篇关于如何大写字符串中每个单词的第一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆