English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin program to check if a character is a letter

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.

Example1: Kotlin programs use if to check for letters

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.

Example2: Kotlin programs use ranges to check for letters

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.

Example# Kotlin program using when to check a letter

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.

Comprehensive Collection of Kotlin Examples