Kotlin How to Convert String to Lowercase Example
In Kotlin, convert a string to lowercase using the
lowercase() function like this: val lower = yourString.lowercase().Examples
InputHELLO
Outputhello
InputKotlin Is Fun
Outputkotlin is fun
Input123 ABC xyz!
Output123 abc xyz!
How to Think About It
To convert a string to lowercase in Kotlin, think of changing every uppercase letter to its lowercase version while leaving other characters unchanged. The
lowercase() function does this easily by scanning the string and converting letters as needed.Algorithm
1
Get the input string.2
Use the lowercase() function to convert all uppercase letters to lowercase.3
Return or print the converted lowercase string.Code
kotlin
fun main() {
val original = "Hello Kotlin!"
val lower = original.lowercase()
println(lower)
}Output
hello kotlin!
Dry Run
Let's trace the string "Hello Kotlin!" through the code
1
Original string
original = "Hello Kotlin!"
2
Convert to lowercase
lower = original.lowercase() -> "hello kotlin!"
3
Print result
Output: "hello kotlin!"
| Step | Value |
|---|---|
| original | Hello Kotlin! |
| lower | hello kotlin! |
Why This Works
Step 1: Use of lowercase()
The lowercase() function scans the string and converts each uppercase letter to its lowercase equivalent.
Step 2: Non-letter characters unchanged
Characters like spaces, punctuation, and numbers remain the same because they have no lowercase form.
Step 3: Returns new string
lowercase() returns a new string and does not change the original string.
Alternative Approaches
lowercase(Locale)
kotlin
import java.util.Locale fun main() { val original = "Hello Kotlin!" val lower = original.lowercase(Locale.getDefault()) println(lower) }
This method allows specifying locale for language-specific lowercase rules.
map with lowercaseChar() (legacy)
kotlin
fun main() {
val original = "Hello Kotlin!"
val lower = original.map { it.lowercaseChar() }.joinToString("")
println(lower)
}This manually converts each character; less efficient and more complex than lowercase().
Complexity: O(n) time, O(n) space
Time Complexity
The function processes each character once, so time grows linearly with string length.
Space Complexity
A new string is created for the result, so space also grows linearly with input size.
Which Approach is Fastest?
lowercase() is optimized and simpler than manual character mapping, making it the best choice.
| Approach | Time | Space | Best For |
|---|---|---|---|
| lowercase() | O(n) | O(n) | Simple, efficient lowercase conversion |
| lowercase(Locale) | O(n) | O(n) | Locale-aware lowercase conversion |
| map with lowercaseChar() | O(n) | O(n) | Manual control but less efficient |
Use
lowercase() for simple and clear lowercase conversion in Kotlin.Forgetting that
lowercase() returns a new string and does not modify the original string.