We have built-in functions for Char case conversion :
fun main() {
println('A'.lowercaseChar()) // a
println('z'.uppercaseChar()) // Z
}
How do we define these functions on our own?
Recall that each character has a unique integer associated with it known as code. The code range for uppercase characters A-Z
is 65..90
and that of lowercase characters a-z
is 97..122
.
So to convert an lowercase character to uppercase character, we just have to increment its code by (97 - 65)
i.e. 32
.
Like String, Char is also immutable i.e. we can’t modify it. We have to create a new Char with the required code.
Following is a Char Extension function to convert it from lowercase to uppercase :
fun Char.uppercaseChar(): Char {
// Convert only if it is lowercase Char
return if (this in 'a'..'z') {
// Create a new Char with the required code
Char(code + ('A'.code - 'a'.code))
} else {
this
}
}