Since you know capitalize()
all you need is to split the string with space as a delimeter to extract each word and apply capitalize()
to each word. Then rejoin all the words.
fun String.capitalizeWords(): String = split(" ").map { it.capitalize() }.joinToString(" ")
use it:
val s = "the quick brown fox"
println(s.capitalizeWords())
will print:
The Quick Brown Fox
Note: this extension does not take in account other chars in the word which may or may not be capitalized but this does:
fun String.capitalizeWords(): String = split(" ").map { it.toLowerCase().capitalize() }.joinToString(" ")
or shorter:
@SuppressLint("DefaultLocale")
fun String.capitalizeWords(): String =
split(" ").joinToString(" ") { it.toLowerCase().capitalize() }