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.

Download Code

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.

Download Code

3. Using none() function

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

Download Code

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.

Download Code

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.

Download Code

That’s all about determining whether a string contains only alphabets in Kotlin.