To check if a string contains only alphabets in Kotlin, you can use the all
function with a predicate that checks if each character is an alphabet.
In this example,
str1
with a value of "HelloWorld"
.all
function with a predicate that checks if each character is an alphabet using Char::isLetter
.all
function returns true
if all characters pass the predicate, otherwise false
.fun main() {
val str1 = "HelloWorld"
val containsOnlyAlphabets = str1.all { it.isLetter() }
println("String contains only alphabets: $containsOnlyAlphabets")
}
String contains only alphabets: true
In this example,
str2
with a value of "Hello123"
.all
function with a predicate that checks if each character is an alphabet using Char::isLetter
.all
function returns true
if all characters pass the predicate, otherwise false
.fun main() {
val str2 = "Hello123"
val containsOnlyAlphabets = str2.all { it.isLetter() }
println("String contains only alphabets: $containsOnlyAlphabets")
}
String contains only alphabets: false
In this tutorial, we learned How to Check if String contains only Alphabets in Kotlin language with well detailed examples.