In kotlin, how to check if the input is alphabetic only.
Input could be anything, a String
, Int
or Double
etc.
For example
val input = readLine()
if(check) {
doSomeTask
}
else doSomethingElse
In kotlin, how to check if the input is alphabetic only.
Input could be anything, a String
, Int
or Double
etc.
For example
val input = readLine()
if(check) {
doSomeTask
}
else doSomethingElse
You can use a regex with the alphabet range:
fun alphabetCheck(input: String): Boolean {
val regex = Regex("[a-zA-Z]+?")
return regex.matches(input)
}
First convert your input to string by using toString()
:
val str = input.toString()
val matchesAlphabet = alphabetCheck(str)
You can check the ascii value of a character as in the example:
fun main(args: Array) {
val c = 'a'
val ascii = c.toInt()
println("The ASCII value of $c is: $ascii")
}
If you look at the ascii table, you can see that alphabetic characters are the one between the values 65 and 90 for capital letters. For small letters you have the interval 97 - 122.
You can have a look here, there are a lot of examples.
for example you can check via
fun isLetters(string: String): Boolean {
return string.all { it.isLetter() }
}
If you want to build an arbitrary lookup (say characters that fit an encoding like base 64) you can do this kind of thing too:
val acceptable = ('a'..'z').plus('A'..'Z').plus("+-/~".asIterable())
So that's using ranges as a quick way of defining a... range of characters, and using a string to easily specify some individual ones (and turning it into an Iterable<Char>
so plus
can add them to the list.
val Char.isAcceptable get() = this in acceptable
"ab+5%".filter(Char::isAcceptable).let { print("VIPs: $it")}
>>>> VIPs: ab+
A good answer for checking if a
String
is entirely alphabetical was given by @HakobHakobyan:String.all { it.isLetter() }
.I will borrow his solution to target a second aspect of your question, that is
Here's another method that checks
Any
input type:and it can be used in an example
main()
like this:The output is
Only the last
String
is entirely alphabetical.