Scala 中每个单词的首字母大写

46

我知道这个方法

val str=org.apache.commons.lang.WordUtils.capitalizeFully("is There any other WAY"))

想知道是否有其他方式以Scala风格进行相同的操作。

4个回答

149

将字符串的第一个字母大写:

"is There any other WAY".capitalize
res8: String = Is There any other WAY

将字符串中每个单词的首字母大写:

"is There any other WAY".split(' ').map(_.capitalize).mkString(" ")
res9: String = Is There Any Other WAY

将字符串的第一个字母大写,其他所有字母小写:

首字母大写,其余字母小写。

"is There any other WAY".toLowerCase.capitalize
res7: String = Is there any other way

将字符串中每个单词的首字母大写,其他字母小写:

"is There any other WAY".toLowerCase.split(' ').map(_.capitalize).mkString(" ")
res6: String = Is There Any Other Way

9
有点复杂,您可以使用split方法获取字符串列表,然后使用capitalize方法来首字母大写,最后使用reduce方法将其合并为一个字符串:
scala> "is There any other WAY".split(" ").map(_.capitalize).mkString(" ")
res5: String = Is There Any Other WAY

2

这个方法可以将每个单词的首字母大写,无论分隔符是什么,不需要任何额外的库。它还可以正确处理撇号。

scala> raw"\b((?<!\b')\w+)".r.replaceAllIn("this is a test, y'all! 'test/test'.", _.group(1).capitalize)
res22: String = This Is A Test, Y'all! 'Test/Test'.

1
注意:对于未来的读者,请确保在将此函数应用于您的字符串之前执行 .toLowerCase - Ian Macalinao
1
不过,如果您想保留首字母缩写或任何其他自定义大写形式,则不要使用.toLowerCase()。在这种情况下:`scala> raw"\b((?as IRS?", _.group(1).capitalize)
res1: String = 但是对于首字母缩写,比如IRS呢?`
- Eugr

-1

无论分隔符如何,将每个单词的首字母大写:

scala> import com.ibm.icu.text.BreakIterator
scala> import com.ibm.icu.lang.UCharacter

scala> UCharacter.toTitleCase("is There any-other WAY", BreakIterator.getWordInstance)
res33: String = Is There Any-Other Way

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接