Kotlin – Check if String contains only Alphabets and Digits

Check if String contains only Alphabets and Digits in Kotlin

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

Char.isLetterOrDigit() function is used to check if the character is an alphabet or a digit.

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 and digits is

str.all { it.isLetterOrDigit() }

Examples

Validate ID number of Employee

Consider that in a company ABC, the employees are given an ID which contains only alphabets and numeric digits.

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

Kotlin Program

fun main() {
    val str = "APPLE123"
    if ( str.all { it.isLetterOrDigit() } ) {
        println("String contains only alphabets and digits.")
    } else {
        println("String does not contain only alphabets and digits.")
    }
}

Output

String contains only alphabets and digits.

Negative Scenario

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

Kotlin Program

fun main() {
    val str = "APPLE - 123"
    if ( str.all { it.isLetterOrDigit() } ) {
        println("String contains only alphabets and digits.")
    } else {
        println("String does not contain only alphabets and digits.")
    }
}

Output

String does not contain only alphabets and digits.

There is a whitespace character and hyphen character in the string. Therefore, the output says that the string does not contain only alphabets and digits.