Saturday 17 July 2021

Capitalize each word of a String in Kotlin

capitalize() the string extension function is got deprecated from Kotlin 1.5 and they have provided an alternative as replaceFirstChar().  Since I'm creating a new extension functon and performing the logic to capitalize the words in the sentence.  We have used Regex() param to the split function, inorder to remove the unnecessary spaces at the end of each words.  In case you are not going to remove those spaces, so you can simply use .split(" ")

fun String.capitalizeWord() = lowercase()
    .joinToString(" ") {

println("thE QuIck    bROwN   FOx".capitalizeWord())
println("thE qUiCk bRown FoX".capitalizeWord())


The Quick Brown Fox
The Quick Brown Fox

Happy Coding :-)