Capitalise every word in String with extension function

Abdullah Nagori picture Abdullah Nagori · Aug 27, 2018 · Viewed 14.9k times · Source

I want to make a extension function in Kotlin, that converts the first letter of each word of the string to upper case

the quick brown fox

to

The Quick Brown Fox

I tried using the capitalize() method. That only though capitalised the first letter of the String.

Answer

user8959091 picture user8959091 · Aug 27, 2018

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