Reputation: 1672
How I can make a function that take a string and return the result whether the string contain alphabet letter only or not.
Upvotes: 2
Views: 9514
Reputation: 381
You could use a simple regular expression to validate the input:
fun isOnlyLetters(word: String): Boolean {
val regex = "^[A-Za-z]*$".toRegex()
return regex.matches(word)}
Alternatively,
^[A-Za-z ]*$
(space after "z")would allow any amount of whitespace (such as in a phrase) at any point in the string (i.e. and still return true).^[A-Za-z ]+$
(*
-> +
) would return false for an empty string(i.e. ensure that there is at least one character in the input, be it a letter or space).Upvotes: 3
Reputation: 9672
function all
returns true
if all characters match the given predicate.
fun String.onlyLetters() = all { it.isLetter() }
if (str.onlyLetters()) {
// only letters
}
else {
}
Upvotes: 9
Reputation: 164089
You can use the function firstOrNull()
to search for the 1st non letter char and compare the result with null
:
fun onlyLetters(s: String): Boolean = (s.firstOrNull { !it.isLetter() } == null)
or as an extension function:
fun String.onlyLetters(): Boolean = (firstOrNull { !it.isLetter() } == null)
Note that this way you will get true
even if the string is empty.
If you don't want this then you should add another condition for the length like:
fun String.onlyLetters(): Boolean = length > 0 && (firstOrNull { !it.isLetter() } == null)
Upvotes: 4
Reputation: 1672
create an extension function isLettersOnly()
/* * This fuction return true only if the string contain a-z or A-Z, * Otherwise false*/
fun String.isLettersOnly(): Boolean {
val len = this.length
for (i in 0 until len) {
if (!this[i].isLetter()) {
return false
}
}
return true
}
1.check a string value
fun main() {
val text = "name"
if (text.isLettersOnly()) {
println("This is contain a-z,A-Z only")
} else {
println("This contain something else")
}
}
output: This is contain a-z,A-Z only
2.check a string value
fun main() {
val text = "name 5"
if (text.isLettersOnly()) {
println("This is contain a-z,A-Z only")
} else {
println("This contain something else")
}
}
output: This contain something else
Upvotes: 0