Kotlin program to capitalize first letter/character of each words in a sentence

Kotlin program to capitalize first letter/character of each words in a sentence :

In this Kotlin programming tutorial, I will show you different ways to capitalize the first letter of each words in a string. We can’t modify a string as it is immutable. We will create one new string from the original string.

Method 1: By splitting and joining the words :

Kotlin provides one method capitalize() to capitalize the first character of a string. For a sentence, we can get the words, capitalize the first letter of each words using this method and join them to create the final string.

fun main() {
    val str = "The quick brown fox jumps over the lazy dog"

    val words = str.split(" ")

    var newStr = ""

    words.forEach {
        newStr += it.capitalize() + " "
    }

    print(newStr.trimEnd())
}

Explanation :

Here, str is the given string. words holds the list of all words in str. Using a forEach method, we are iterating through the words and capitalizing each using capitalize() method. Each words are concatenated to newStr string variable with a blank space between each.

This program will also add one extra blank space to the end of the final string, that we are removing using trimEnd() method.

It will print the below output :

The Quick Brown Fox Jumps Over The Lazy Dog

Using split and joinToString in one line :

We can re-write the above to do everything just in one line like below :

fun main() {
    val str = "The quick brown fox jumps over the lazy dog"

    var newStr = str.split(" ").joinToString(" ") { it.capitalize() }.trimEnd();

    print(newStr)
}

This is the beauty of Kotlin.

It will print the same output.

Using extension function :

We can convert the above to an extension function :

fun String.capitalizeFirstLetter() = this.split(" ").joinToString(" ") { it.capitalize() }.trimEnd()

fun main() {
    val str = "The quick brown fox jumps over the lazy dog"

    print(str.capitalizeFirstLetter())
}

Any other way to do that ? Drop one comment below if you know any other method to solve it :)

Similar tutorials :