Kotlin – Check if string contains only alphabets

Check if String contains only Alphabets in Kotlin

To check if given string contains only Alphabet characters in Kotlin, check if all of the characters in the string is an alphabet using String.all() function and Char.isLetter() function.

Char.isLetter() function is used to check if the character is an alphabet.

String.all() function is used to check if all the characters in the given string satisfy the given condition.

The boolean expression to check if given string str contains only alphabets is

str.all { it.isLetter() }

Examples

Validate Firstname

In the following program, we take a string value in str, say firstname of a person and validate this string to check if it contains only alphabets.

Kotlin Program

fun main() {
    val str = "Ram"
    if ( str.all { it.isLetter() } ) {
        println("String contains only alphabets.")
    } else {
        println("String does not contain only alphabets.")
    }
}

Output

String contains only alphabets.

Negative Scenario

In the following program, we take a string in str such that there are characters other than alphabets, and run the same code from the previous example.

Kotlin Program

fun main() {
    val str = "Ram@123"
    if ( str.all { it.isLetter() } ) {
        println("String contains only alphabets.")
    } else {
        println("String does not contain only alphabets.")
    }
}

Output

String does not contain only alphabets.

There are digits and @ character in the string, which are not alphabets. Therefore, the output says that the string does not contain only alphabets.