Kotlin String.capitalize() and replaceFirstChar()
Kotlin’s String.capitalize() function returns a copy of a string with its first character converted to title case. However, capitalize() is deprecated in current Kotlin versions. New Kotlin code should use replaceFirstChar() instead.
If the string is empty, or its first character does not need conversion, the resulting text remains unchanged. Only the first character is affected; the rest of the string retains its original case.
Modern Kotlin Replacement for capitalize()
The recommended replacement uses replaceFirstChar(). The lambda receives the first character, which can then be converted with titlecase(). This approach is shown in the current Kotlin standard library documentation.
fun main() {
val text = "kotlin tutorial examples"
val result = text.replaceFirstChar { character ->
if (character.isLowerCase()) character.titlecase()
else character.toString()
}
println(result)
}
Output
Kotlin tutorial examples
For a shorter expression, use replaceFirstChar(Char::titlecase) when applying title case unconditionally is suitable:
val result = text.replaceFirstChar(Char::titlecase)
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
This original example demonstrates the deprecated API. In a current Kotlin project, replace the capitalize() call with the replaceFirstChar() approach shown above.
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
Capitalize the First Letter of Every Word with replaceFirstChar()
For current Kotlin code, split the sentence into words, transform each word with replaceFirstChar(), and join the results. The following example also handles runs of whitespace between words:
fun main() {
val sentence = "kotlin string capitalization example"
val title = sentence
.trim()
.split(Regex("\\s+"))
.joinToString(" ") { word ->
word.replaceFirstChar { character ->
if (character.isLowerCase()) character.titlecase()
else character.toString()
}
}
println(title)
}
Output
Kotlin String Capitalization Example
This produces title-like text, but it also normalizes consecutive whitespace to a single space. If the original spacing must be preserved, transform the text with a regular expression instead of splitting and joining it.
Preserve Whitespace While Capitalizing Kotlin Words
The following version finds each word boundary and changes only the character that follows it. Spaces, tabs, and line breaks elsewhere in the string remain intact.
fun main() {
val text = "kotlin string\tfunctions"
val result = Regex("(^|\\s)(\\p{L})").replace(text) { match ->
match.groupValues[1] + match.groupValues[2].titlecase()
}
println(result)
}
Output
Kotlin String Functions
Kotlin titlecase() vs uppercase()
titlecase() converts a character to its title-case representation, while uppercase() converts it to uppercase. They often produce the same visible result for English letters, but they express different casing operations and may behave differently for some Unicode characters.
Use titlecase() when capitalizing the beginning of a word. Use uppercase() when the requirement is specifically to convert a character or complete string to uppercase.
val capitalized = "kotlin".replaceFirstChar(Char::titlecase)
val uppercaseText = "kotlin".uppercase()
println(capitalized)
println(uppercaseText)
Output
Kotlin
KOTLIN
Kotlin String Capitalization Checklist
- Use
replaceFirstChar()instead of deprecatedcapitalize()in new Kotlin code. - Use
titlecase()when changing the first character of a word. - Remember that capitalizing a string changes only its first character, not every word.
- Decide whether splitting and joining may normalize whitespace unexpectedly.
- Test empty strings, strings beginning with digits or symbols, existing uppercase text, and non-English characters when they are valid inputs.
Frequently Asked Questions about Kotlin String Capitalization
Is String.capitalize() deprecated in Kotlin?
Yes. String.capitalize() is deprecated. Use replaceFirstChar() with titlecase() for new Kotlin code.
How do I capitalize only the first character of a Kotlin string?
Use text.replaceFirstChar(Char::titlecase). If the first character should be changed only when it is lowercase, check isLowerCase() inside the lambda.
Does replaceFirstChar() fail on an empty Kotlin string?
No. When the string is empty, replaceFirstChar() returns the empty string and does not invoke its transformation function.
How do I capitalize every word in a Kotlin sentence?
Split the sentence into words, call replaceFirstChar() for each word, and combine the results with joinToString(). Use a regular-expression replacement instead when the original whitespace must remain unchanged.
Does capitalizing a Kotlin string lowercase its remaining characters?
No. Capitalizing the first character does not change the remaining characters. For example, capitalizing kOTLIN produces KOTLIN, not Kotlin. Convert the remaining text to lowercase separately if that is required.
Choosing the Kotlin Capitalization Method
Use replaceFirstChar() to capitalize the beginning of a string in current Kotlin code. Apply it to each word when every word must begin with title case, and use uppercase() only when the complete string should be uppercase. The earlier capitalize() examples remain useful for understanding older Kotlin code, but the deprecated function should be replaced when maintaining a current project.
Continue with the Kotlin Tutorial for more Kotlin string and language examples.
TutorialKart.com