Determine whether a given string is alphanumeric in Kotlin
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
fun isLettersOrDigits(chars: String): Boolean { for (c in chars) { if (c !in 'A'..'Z' && c !in 'a'..'z' && c !in '0'..'9') { return false } } return true } fun main() { val chars = "Kotlin2020" println("IsAlphaNumeric: ${isLettersOrDigits(chars)}") // true } |
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.
|
1 2 3 4 5 6 7 8 9 10 |
fun isLettersOrDigits(chars: String): Boolean { return chars.filter { it in 'A'..'Z' || it in 'a'..'z' || it in '0'..'9' } .length == chars.length } fun main() { val chars = "Kotlin2020" println("IsAlphaNumeric: ${isLettersOrDigits(chars)}") // true } |
3. Using none() function
You can also use the none() function, which returns true when no characters match the given condition.
|
1 2 3 4 5 6 7 8 9 |
fun isLettersOrDigits(chars: String): Boolean { return chars.none { it !in 'A'..'Z' && it !in 'a'..'z' && it !in '0'..'9' } } fun main() { val chars = "Kotlin2020" println("IsAlphaNumeric: ${isLettersOrDigits(chars)}") // true } |
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.
|
1 2 3 4 5 6 7 8 9 |
fun isLettersOrDigits(chars: String): Boolean { return chars.all { it.isLetterOrDigit() } } fun main() { val chars = "Kotlin2020" println("IsAlphaNumeric: ${isLettersOrDigits(chars)}") // true } |
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.
|
1 2 3 4 5 6 7 8 9 |
fun isLettersOrDigits(chars: String): Boolean { return chars.matches("^[a-zA-Z0-9]*$".toRegex()) } fun main() { val chars = "Kotlin2020" println("IsAlphaNumeric: ${isLettersOrDigits(chars)}") // true } |
That’s all about determining whether a given string is alphanumeric in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)