Check if a string contains only alphabets in Kotlin
This article explores different ways to check if a given string contains only alphabets in Kotlin.
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 an alphabet or not.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
fun isLetters(string: String): Boolean { for (c in string) { if (c !in 'A'..'Z' && c !in 'a'..'z') { return false } } return true } fun main() { val string = "Kotlin" println("Is Alphabet: ${isLetters(string)}") // true } |
2. Using filter() function
Alternatively, you can filter the string for non-alphabetic characters using the filter() function and then use the length property to compare the length of the filtered string with the original string. If length is found to be the same, then we can say that all characters in the string are alphabets.
|
1 2 3 4 5 6 7 8 9 |
fun isLetters(string: String): Boolean { return string.filter { it in 'A'..'Z' || it in 'a'..'z' }.length == string.length } fun main() { val string = "Kotlin" println("Is Alphabet: ${isLetters(string)}") // true } |
3. Using none() function
You can also use the none() function, which returns true if no characters match the given predicate.
|
1 2 3 4 5 6 7 8 9 |
fun isLetters(string: String): Boolean { return string.none { it !in 'A'..'Z' && it !in 'a'..'z' } } fun main() { val string = "Kotlin" println("Is Alphabet: ${isLetters(string)}") // true } |
4. Using all() function
The lambda expression in all the above functions can be effectively replaced by the isLetter() function. Here’s an example using the all() function, which is the opposite of none(), i.e., it returns true if all characters match the given predicate.
|
1 2 3 4 5 6 7 8 9 |
fun isLetters(string: String): Boolean { return string.all { it.isLetter() } } fun main() { val string = "Kotlin" println("Is Alphabet: ${isLetters(string)}") // true } |
5. Using Regular Expressions
Finally, you can use the regular expression ^[a-zA-Z]*$, which matches the string against alphabets. We can use it with the matches() function to check if the string matches the given regex.
|
1 2 3 4 5 6 7 8 9 |
fun isLetters(string: String): Boolean { return string.matches("^[a-zA-Z]*$".toRegex()) } fun main() { val string = "Kotlin" println("Is Alphabet: ${isLetters(string)}") // true } |
That’s all about determining whether a string contains only alphabets 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 :)