stringkotlincharstring-matchingtextmatching

Check if a string contains only letters


How can I make a function that takes a string and returns the result whether the string contains only alphabet letters or not?


Solution

  • function all returns true if all characters match the given predicate.

    fun String.onlyLetters() = all { it.isLetter() }
    
    if (str.onlyLetters()) {
    // only letters
    }
    else {
    
    }