45

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 the Same.

something in Scala Style

Govind Singh
  • 15,282
  • 14
  • 72
  • 106

4 Answers4

148

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
Michael Zajac
  • 55,144
  • 7
  • 113
  • 138
9

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

scala> "is There any other WAY".split(" ").map(_.capitalize).mkString(" ")
res5: String = Is There Any Other WAY
Nikita
  • 4,435
  • 3
  • 24
  • 44
Ende Neu
  • 15,581
  • 5
  • 57
  • 68
2

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'.
Eugr
  • 76
  • 2
  • 1
    Note to future readers: make sure to `.toLowerCase` before applying this function to your string. – Ian Macalinao Sep 30 '18 at 19:39
  • 1
    Not if you want to preserve acronyms or any other custom capitalization, though. In this case do not use .toLowerCase(): `scala> raw"\b((?<!\b')\w+)".r.replaceAllIn("But what about acronyms, such as IRS?", _.group(1).capitalize) res1: String = But What About Acronyms, Such As IRS?` – Eugr Oct 01 '18 at 23:08
-1

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