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

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

问题描述

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?

示例:

  • 乔恩·斯基特 -> 乔恩·斯基特
  • miles o'Brien -> Miles O'Brien(B 仍然是大写,这排除了 Title Case)
  • 老麦当劳 -> 老麦当劳*
  • 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天全站免登陆