string 将 Scala 中每个单词的第一个字母大写

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25787829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:16:44  来源:igfitidea点击:

Capitalize the first letter of every word in Scala

stringscalacapitalization

提问by Govind Singh

I know this way

我知道这样

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

Want to know is there any other way to do Same.

想知道有没有其他方法可以做到。

something in Scala Style

Scala 风格的东西

回答by Michael Zajac

Capitalize the first letter of a string:

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

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

Capitalize the first letter of every word in a string:

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

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

Capitalize the first letter of a string, while lower-casing everything else:

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

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

Capitalize the first letter of every word in a string, while lower-casing everything else:

将字符串中每个单词的第一个字母大写,而其他所有内容都小写:

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

回答by Ende Neu

A bit convoluted, you can use split to get a list of strings and then use capitalize, then reduce to get back the string:

有点复杂,您可以使用 split 来获取字符串列表,然后使用大写,然后减少来取回字符串:

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

回答by Eugr

This one will capitalize every word regardless of the separator and doesn't require any additional libraries. It will also handle apostrophe correctly.

无论分隔符如何,这个都将大写每个单词,并且不需要任何额外的库。它还将正确处理撇号。

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'.

回答by Sergey Povaliaev

To capitalize the first letter of every word despite of a separator:

尽管有分隔符,但要大写每个单词的第一个字母:

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