this is my/his house - Input
This Is My/His House - Output
In Swift ,there is capitalized method which gives the above output ,is there any way to achieve the same in kotlin
this is my/his house - Input
This Is My/His House - Output
In Swift ,there is capitalized method which gives the above output ,is there any way to achieve the same in kotlin
In Kotlin
val s = "this is my/his house"
println(s.toCapitalizeEachWord())
Extension Function:
fun String.toCapitalizeEachWord() : String{
return this.split(" ").map {
if(it.contains("/")){
it.split("/").map { word -> word.replaceFirstChar { firstChar -> firstChar.uppercase() }
}.joinToString("/")
}else{
it.replaceFirstChar { firstChar -> firstChar.uppercase() }
}
}.joinToString(" ") }
Input: this is my/his house
Output: This Is My/His House
You have to capitalize every word.
However String.capitalize()
is now deprecated.
The easer solution is:
fun String.capitalizeSentence(): String =
this.trim().split("\\s+".toRegex())
.joinToString(" ") { it.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.ROOT) else it.toString() } }
Well many has posted correct core logic or main logic so you just needed to add little bit your own logic to work . Anyways below method is tested with your requirement and it is working fine
fun String.capitalizeEachWord() : String{
return this.split(" ").map {
if(it.contains("/")){
it.split("/").map { word -> word.replaceFirstChar { firstChar -> firstChar.uppercase() }
}.joinToString("/")
}else{
it.replaceFirstChar { firstChar -> firstChar.uppercase() }
}
}.joinToString(" ")
}