Capitalize first letter of a String in Kotlin
This article explores different ways to capitalize the first letter of a String in Kotlin.
1. Capitalize first letter
The simplest solution is to use the toUpperCase() function. It returns a copy of the string with its first letter upper-cased. If the string is empty or already starts with an upper case letter, it returns the original string.
|
1 2 3 4 5 6 7 8 |
fun capitalize(str: String): String? { return str.capitalize() } fun main() { val str = "capitalize me" println(capitalize(str)) // Capitalize me } |
Since String is immutable in Kotlin, no modifications are possible in the original string. If the string can be null, use the Elvis operator with null check:
|
1 2 3 4 5 6 7 8 |
fun capitalize(str: String?): String? { return str?.capitalize() ?: str } fun main() { val str = "capitalize me" println(capitalize(str)) // Capitalize me } |
2. Capitalize each word
The idea is to get a list of all whitespace-separated words, and capitalize each word using the toUpperCase() function. The following solution demonstrates this.
|
1 2 3 4 5 6 7 8 9 |
fun capitalize(str: String): String { return str.trim().split("\\s+".toRegex()) .map { it.capitalize() }.joinToString(" ") } fun main() { val str = "capitalize me" println(capitalize(str)) // Capitalize Me } |
We can merge the call chain to joinToString() with a transform function:
|
1 2 3 4 5 6 7 8 9 |
fun capitalize(str: String): String? { return str.trim().split("\\s+".toRegex()) .joinToString(" ") { it.capitalize() } } fun main() { val str = "capitalize me" println(capitalize(str)) // Capitalize Me } |
That’s all about capitalizing the first letter of a String in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)