This article explores different ways to determine whether a given string is alphanumeric in Kotlin. A string is called alphanumeric if it consists of only alphabets and numbers.

1. Using for loop

In Kotlin, you can iterate over all characters in the string using a for-loop and check if each character is alphanumeric or not.

Download Code

2. Using filter() function

Alternatively, you can filter the string with the filter() function to skip the non-alphanumeric characters. Then if the length of the filtered string is the same as the length of the original string, you can say that all characters in the string are alphanumeric.

Download Code

3. Using none() function

You can also use the none() function, which returns true when no characters match the given condition.

Download Code

4. Using all() function

Another plausible way is using the all() function, which is the opposite of none(), i.e., it returns true if all characters match the given condition. The predicate can be replaced by isLetterOrDigit() function.

Download Code

5. Using Regular Expressions

Finally, you can call the matches() function using the regular expression ^[a-zA-Z0-9]*$, which matches the string against alphanumeric characters.

Download Code

That’s all about determining whether a given string is alphanumeric in Kotlin.