Kotlin String.capitalize()

String.capitalize() returns a copy of this string having its first letter upper-cased.

String.capitalize() returns the original string, if it’s empty or already starts with an upper-case letter.

To capitalize first character of each word in the given sentence, refer the second example provided below.

Example 1 – Capitalize First Letter in String

In this example, we will take a string, and make the first letter of this string as Uppercase using String.capitalize() method.

Kotlin Program – example.kt

fun main(args: Array<String>) {

    var str = "kotlin tutorial examples"

    val strModified = str.capitalize()

    print(strModified)
}

Output

Kotlin tutorial examples

Example 2 – Capitalize First Letter for each Word in String

In this example, we will take a string, and make the first letter of each word in this string as Uppercase using Kotlin For Loop and String.capitalize() method.

Kotlin Program – example.kt

fun main(args: Array<String>) {

    val str = "kotlin tutorial examples"

    val words = str.split(" ").toMutableList()

    var output = ""

    for(word in words){
        output += word.capitalize() +" "
    }

    output = output.trim()

    print(output)
}

Output

Kotlin Tutorial Examples

Conclusion

In this Kotlin TutorialKotlin String Capitalize, we have learnt how to use to capitalize() function to convert first character of a String or each word of String to uppercase with examples.