
1. Overview
In this article, we will learn to capitalize the first letter of each word in Kotlin.
Since Kotlin strings are immutable, meaning all modification operations create a new string instead of modifying the original string in place.
So the following solutions always return the result as a new string.
2. Kotlin capitalize the first letter of each word
You can create an extension function to capitalize the first letter of each word in the String
. Since capitalize function is deprecated, we will use replaceFirstChar
function for this extension function.
- Split the string using space
- Take each word and call the
replaceFirstChar
function on the original string and pass the transform function as input. The transform function takes the first character and converts it to an uppercase character using theuppercase()
function. - Append the words using the
joinToString
function
Since Kotlin strings are immutable, it always returns a copy of the original string. If the original string is empty, then returns the original string itself.
fun main() { val str = "capitalize tHe first character of all words" println(str.capitalizeWords()) } fun String.capitalizeWords(): String = split(" ").map { it.lowercase().replaceFirstChar( { it.uppercase() }) }.joinToString(" ")
You can shorten the above extension function further as:
fun String.capitalizeWords(): String = split(" ").joinToString(" ") { it.lowercase().replaceFirstChar( { it.uppercase() }) }
3. Conclusion
To sum up, we have learned to capitalize the first letter of each word in a String. You can refer to this article to capitalize only the first letter in the string.
You can find code samples in our GitHub repository.