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()
    .split("\\s+".toRegex())
    .joinToString(" ") {
        it.trim().replaceFirstChar(Char::titlecase)
    }

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

Output:

The Quick Brown Fox
The Quick Brown Fox

Happy Coding :-)