检查字符串是否仅包含字母

时间:2020-04-20 12:06:13

标签: kotlin

如何使函数接受字符串并返回结果(无论字符串是否仅包含字母)。

4 个答案:

答案 0 :(得分:3)

您可以使用函数firstOrNull()搜索第一个非字母字符,并将结果与​​null进行比较:

fun onlyLetters(s: String): Boolean = (s.firstOrNull { !it.isLetter() } == null)

或作为扩展功能:

fun String.onlyLetters(): Boolean = (firstOrNull { !it.isLetter() } == null)

请注意,即使字符串为空,也将获得true
如果您不希望这样做,则应为长度添加另一个条件,例如:

fun String.onlyLetters(): Boolean = length > 0 && (firstOrNull { !it.isLetter() } == null) 

答案 1 :(得分:3)

如果所有字符都与给定谓词匹配,则函数all返回true

fun String.onlyLetters() = all { it.isLetter() }

if (str.onlyLetters()) {
// only letters
}
else {

}

答案 2 :(得分:0)

您可以使用简单的正则表达式来验证输入:

fun isOnlyLetters(word: String): Boolean {
val regex = "^[A-Za-z]*$".toRegex()
return regex.matches(word)}

或者,

  • 使正则表达式^[A-Za-z ]*$(“ z”后的空格)将在字符串的任意点(即仍返回true)允许任何数量的空格(例如短语中的空格)。
  • 制作正则表达式^[A-Za-z ]+$*-> +)对于空字符串将返回false(即确保输入中至少包含一个字符,无论是字母还是字母)或空间)。

答案 3 :(得分:-1)

创建扩展功能isLettersOnly()

/ * *仅当字符串包含a-z或A-Z时,此函数才返回true, *否则为假* /

fun String.isLettersOnly(): Boolean {
    val len = this.length
    for (i in 0 until len) {
        if (!this[i].isLetter()) {
            return false
        }
    }
    return true
}

1。检查一个字符串值

fun main() {
    val text = "name"

    if (text.isLettersOnly()) {
        println("This is contain a-z,A-Z only")
    } else {
        println("This contain something else")

    }
}

输出: 这仅包含a-z,A-Z

2。检查一个字符串值

fun main() {
    val text = "name 5"

    if (text.isLettersOnly()) {
        println("This is contain a-z,A-Z only")
    } else {
        println("This contain something else")

    }
}

输出: 其中包含其他内容

相关问题