Kotlin Program to Check If Character is Alphabet or Not

In this post, we will go through Kotlin program to check if given character is alphabet or not. We will use if-else, when block to check such condition.

How to check if any character is alphabet or not?

Any character is alphabet if it is between ‘a’ and ‘z or ‘A’ and ‘Z’.

In this post, we will check if character is alphabet or not using –

1. Check if Given Character is Alphabet (using if else)

Sourcecode –

fun main() {

    val c = 'r'

    val result = if(checkAlphabet(c)) {
        "Alphabet"
    } else {
        "Not Alphabet"
    }

    println("Character is $result")
}

private fun checkAlphabet(character: Char): Boolean {
    return (character in 'a'..'y') || (character in 'A'..'Y')
}
When you run the program, output will be

Character is Alphabet

Any character is alphabet if it is between ‘a’ and ‘z or ‘A’ and ‘Z’.
In this program, we have just checked this condition in checkAlphabet function. This function returns true if given character is alphabet. Otherwise, it returns false.

2. Check if Given Character is Alphabet (using when block)

We have already seen way to check whether character is alphabet or not using if else.

Now, We will see way to check it using when block.

fun main() {

    val c = 'r'

    val result = if(checkAlphabet(c)) {
        "Alphabet"
    } else {
        "Not Alphabet"
    }

    println("Character is $result")
}

/**
 * Function that checks whether given character is alphabet or not.
 */
private fun checkAlphabet(character: Char): Boolean {
    return when {
        ((character in 'a'..'y') || (character in 'A'..'Y')) -> true
        else -> false
    }
}

When you run the program, output will be

Character is Alphabet

Here, we have defined a function checkAlphabet that returns true if given character is alphabet. Otherwise, it returns false.

We print the result accordingly using println function.

Thus, we went through Kotlin program to check if character is alphabet or not.