2014-09-11 1 views

Répondre

80

Capitaliser la première lettre d'une chaîne:

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

Capitaliser la première lettre de chaque mot dans une chaîne:

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

Capitaliser la première lettre d'une chaîne, alors que tout inférieur boîtier autre:

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

Capitaliser la première lettre de chaque mot dans une chaîne, alors que tout inférieur boîtier autre:

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

Un peu alambiquée, vous pouvez utiliser Fractionner pour obtenir une liste de chaînes, puis utilisez capitaliser, puis réduire pour revenir la chaîne:

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

Pour mettre la première lettre de chaque mot en dépit d'un séparateur:

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

Celui-ci va capitaliser chaque mot indépendamment du séparateur et ne nécessite aucune bibliothèque supplémentaire. Il va également gérer correctement l'apostrophe.

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