Capitalise every word in String with extension function
Asked Answered
L

10

41

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.

Lacework answered 27/8, 2018 at 15:51 Comment(2)
So, where are you stuck?Iranian
i am using .capitalized() method but by using this method it effects only "The" but i am trying to did it in all sentenceLacework
H
111

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() }
Hadleigh answered 27/8, 2018 at 21:39 Comment(6)
@SamuelKodytek I approved dropping it although I like it being there as I like this being there although it's useless too.Hadleigh
cheers! I understand your point, though I think, if you are already using the arrow notation, you should specify the name of the variable, for example: word -> //More codeReincarnation
@SamuelKodytek that would make it more readable but as I said I like it and thisHadleigh
I understand :)Reincarnation
map can be simplified by merging with joinToString. Like, split(" ").joinToString(" ") { it.capitalize() }Johannisberger
Note, that String.capitalize() is deprecated now and you should use replaceFirstChar insteadGeek
G
24

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

fun String.capitalizeWords(): String = split(" ").joinToString(" ") { it.capitalize() }
Graubert answered 12/6, 2019 at 19:9 Comment(0)
A
10

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() }
    }
}
Accusatorial answered 29/7, 2021 at 11:43 Comment(0)
L
8

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.

Lead answered 8/8, 2020 at 6:9 Comment(0)
R
5

Latest elegant solution without any deprecated constuctions

fun String.toCamelCase(delimiter: String = " "): String {
    return split(delimiter).joinToString(delimiter) { word ->
        word.replaceFirstChar(Char::titlecaseChar)
    }
}
Rackley answered 7/1, 2023 at 10:3 Comment(1)
It should be lowercase first before capitalized -> word.lowercase().replaceFirstChar(Char::titlecaseChar)Rahm
M
1

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

query.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() }
Mecklenburg answered 8/7, 2022 at 9:18 Comment(0)
C
1

Another solution without deprecated methods:

fun String.capitalizeWords(): String =
    split(" ").joinToString(" ") { w -> w.replaceFirstChar { c ->  c.uppercaseChar() } }

Chavira answered 4/10, 2022 at 23:49 Comment(0)
U
0

New way to capitalize the first character of string word. As capitalize() is deprecated now following is the way to achieve this in kotlin.

        val string="the quick brown fox"

        val result= string.split(" ").joinToString(" ") {
            it.replaceFirstChar {it1 ->
                it1.uppercase()
            }
        }
        println("Result::$result")

upper block of code prints:

The Quick Brown Fox
Urbain answered 12/9, 2023 at 7:11 Comment(0)
V
0

My approach will capitalise every word regardless of separators;

Extension Function

fun String.capitaliseEachWord(): String {
    val regex = "(\\b[a-z](?!\\s))".toRegex()
    return this.replace(regex) { it.value.uppercase() }
}

Usage

val input = "capitalise the/words*in&this    string"
val output = input.capitaliseEachWord()
print(output)

Result

Capitalise The/Words*In&This    String
Vanwinkle answered 19/2 at 18:13 Comment(0)
G
-1

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())
  }
}
Gamez answered 14/6, 2021 at 14:41 Comment(1)
'capitalize(): String' is deprecated. Use replaceFirstChar instead.Callous

© 2022 - 2024 — McMap. All rights reserved.