fun isAplhabetical(input: Any): Boolean {
when (input) {
// if the input is a String, check all the Chars of it
is String -> return input.all { it.isLetter() }
// if input is a Char, just check that single Char
is Char -> return input.isLetter()
// otherwise, input doesn't contain any Char
else -> return false
}
}
它可以用在main()这样的例子中:
fun main() {
val a = "Some non-numerical input"
val b = "45"
val c = "Some numbers, like 1, 2, 3, 4 and so on"
val d: Int = 42
val e: Double = 42.42
val f: Float = 43.4333f
val g = "This appears as entirely alphabetical" // but contains whitespaces
val h = "ThisIsEntirelyAlphabetical"
println("[$a] is" + (if (isAplhabetical(a)) "" else " not") + " (entirely) alphabetical")
println("[$b] is" + (if (isAplhabetical(b)) "" else " not") + " (entirely) alphabetical")
println("[$c] is" + (if (isAplhabetical(c)) "" else " not") + " (entirely) alphabetical")
println("[$d] is" + (if (isAplhabetical(d)) "" else " not") + " (entirely) alphabetical")
println("[$e] is" + (if (isAplhabetical(e)) "" else " not") + " (entirely) alphabetical")
println("[$f] is" + (if (isAplhabetical(f)) "" else " not") + " (entirely) alphabetical")
println("[$g] is" + (if (isAplhabetical(g)) "" else " not") + " (entirely) alphabetical")
println("[$h] is" + (if (isAplhabetical(h)) "" else " not") + " (entirely) alphabetical")
}
输出是
[Some non-numerical input] is not (entirely) alphabetical
[45] is not (entirely) alphabetical
[Some numbers, like 1, 2, 3, 4 and so on] is not (entirely) alphabetical
[42] is not (entirely) alphabetical
[42.42] is not (entirely) alphabetical
[43.4333] is not (entirely) alphabetical
[This appears as entirely alphabetical] is not (entirely) alphabetical
[ThisIsEntirelyAlphabetical] is (entirely) alphabetical
6条答案
按热度按时间wztqucjr1#
你可以看看here,有很多例子。
例如,您可以通过
inkz8wg92#
检查
String
是否完全按字母顺序排列的一个很好的答案是由@HakobHakobyan给出的:String.all { it.isLetter() }
。我将借用他的解决方案来针对你问题的第二个方面,即
下面是另一个检查
Any
输入类型的方法:它可以用在
main()
这样的例子中:输出是
只有最后一个
String
完全是字母顺序。g0czyy6m3#
你可以使用正则表达式和字母表范围:
首先使用
toString()
将输入转换为字符串:nlejzf6q4#
你可以检查一个字符的值,如示例所示:
如果您查看ascii table,您可以看到字母字符是大写字母的值65和90之间的字符。对于小写字母,间隔为97 - 122。
xmakbtuz5#
如果你想构建一个任意的查找(比如适合base64编码的字符),你也可以这样做:
所以这是使用范围作为一种快速的方式来定义一个...字符范围,并使用字符串轻松指定一些单个字符(并将其转换为
Iterable<Char>
,以便plus
可以将它们添加到列表中。egmofgnx6#
可以按如下方式完成: