2014-09-11 10 views

risposta

80

Capitalizzare la prima lettera di una stringa:

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

maiuscolo la prima lettera di ogni parola in una stringa:

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

maiuscolo la prima lettera di una stringa, mentre tutto inferiore dell'involucro altro:

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

maiuscolo la prima lettera di ogni parola in una stringa, mentre tutto inferiore dell'involucro altro:

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

Un po 'contorto, è possibile utilizzare diviso per ottenere una lista di stringhe e quindi utilizzare capitalizzare, poi ridurre a tornare stringa:

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

Per rendere maiuscola la prima lettera di ogni parola, nonostante di un separatore:

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 
0

Questo capitalizza ogni parola indipendentemente dal separatore e non richiede alcuna libreria aggiuntiva. Gestirà anche l'apostrofo correttamente.

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