English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of Kotlin Examples
In this program, you will learn how to check if a given character is a letter in Kotlin. This can be done using if-else statements or with the help of when expressions.
fun main(args: Array<String>) { val c = '*' if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') println("$c is a letter.") else println("$c is not a letter.") }
When running the program, the output is:
* is not a letter.
Like Java, in Kotlin, char variables store the ASCII values of characters (0 to127between the numbers) instead of the characters themselves.
and lowercase letters start from97to122. The ASCII values of uppercase letters start from65to90.
That's why, we need to check in 'a'(97) and 'z'(122) to compare the variable c. Similarly, we also check 'A'(65) to 'Z'(9uppercase letters between 0) and 'Z'(
The following is the equivalent Java code for the program:Java program to check if a character is a letter
You can use Range instead of comparison to solve this problem.
fun main(args: Array<String>) { val c = 'a' if (c in 'a'..'z' || c in 'A'..'Z') println("$c is a letter.") else println("$c is not a letter.") }
When running the program, the output is:
a is a letter.
You can even use a when expression instead of a question.
fun main(args: Array<String>) { val c = 'C' when { (c in 'a'..'z' || c in 'A'..'Z') -> println("$c is a letter.") else -> println("$c is not a letter.") } }
When running the program, the output is:
C is a letter.