Capitalise every word in String with extension function

Viewed 18189

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.

6 Answers

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

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

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

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.

capitalise() is now deprecated and kotlin suggests to use replaceFirstChar instead

fun camelCase(string: String, delimiter: String = " ", separator: String = " "): String {
    return string.split(delimiter).joinToString(separator = separator) {
        it.lowercase().replaceFirstChar { char -> char.titlecase() }
    }
}

Another way you could do this with a transform:

fun String.capitalizeWords() = split(' ').joinToString(" ", transform = String::capitalize)

And a test for it:

class StringExtensionTest {
  @Test
  fun `test capitalize a sentance`() = run {
    Assert.assertEquals("Abba Sill Med Extra", "abba sill med extra".capitalizeWords())
  }
}

String#capitalize() is deprecated. use this instead:

query.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() }
Related