Capitalise every word in String with extension function

Why not use an extension property instead?

val String.capitalizeWords
    get() = this.toLowerCase().split(" ").joinToString(" ") { it.capitalize() }

Which can be called like:

val test = "THIS iS a TeST."
println(test.capitalizeWords)

Which would display:

This Is A Test.

Personally I think properties should be used for returns with no parameters.


It can be done in a simpler way than the accepted answer offers, check this:

fun String.capitalizeWords(): String = split(" ").joinToString(" ") { it.capitalize() }

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() }