Kotlin Program to Check If Character is Alphabet or Not

Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners. Also, if you are interested in content writing, you can mail us at tutorialwing@gmail.com.

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.

Support Us

If you like Tutorialwing and would like to contribute, you can email an article on any educational topic at tutorialwing@gmail.com. We would love to publish your article. See your article on Tutorialwing and help others with your knowledge. Follow Facebook, LinkedIn, Google+, Twitter, Youtube for latest updates.
Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners