Code access
Code access
We can access the code of any character using the Char#code field.
 fun main() {
    println('A'.code) // Prints "65"
    println('A'.code..'Z'.code) // Prints "65..90"
    println('0'.code..'9'.code) // Prints "48..57"
    println('\n'.code) // Prints "10"
    println('#'.code)  // Prints "35"
}
 
Type check
Type check
We have several built-in functions like isLetter(), isDigit(), isLowerCase(), isUppercase() etc. :
 fun main() {
    println('A'.isLetter())     // true
    println('z'.isLetter())     // true
    println('0'.isLetter())     // false
    println('0'.isDigit())      // true
    println('A'.isUpperCase())  // true
    println('z'.isUpperCase())  // false
    println('x'.isLowerCase())  // true
}
 
Case conversions
Case conversions
We can convert a character from uppercase to lowercase and vice-versa using the lowercaseChar() & uppercaseChar() functions respectively :
 fun main() {
    println('A'.lowercaseChar()) // a
		println('z'.uppercaseChar()) // Z
}
 
Parse Digit
Parse Digit
If a character is digit, then we can parse it to an Int. For example - ‘5’ → 5. We use the digitToInt() function for this :
 fun main() {
    listOf('0', '2', '5', '7', '8').forEach {
        println(it.digitToInt())
    }
    println('a'.digitToInt()) // throws IllegalArgumentException
}
/* Output :
0
2
5
7
8
Exception in thread "main" java.lang.IllegalArgumentException: Char a is not a decimal digit
 */
 
To avoid exception being thrown in case of non-digit characters, we can use the safe function - toIntOrNull() :
 fun main() {
    println('a'.digitToIntOrNull()) // Prints null instead
}
 
Equality check
Equality check
To check whether two characters are equal, we can use the equals() function :
 fun Char.equals(
		other: Char, 
		ignoreCase: Boolean = false // Whether to ignore case
): Boolean
 
Example :
 fun main() {
    println('A'.equals('a')) // false
		println('A'.equals('a', ignoreCase = true)) // true
}