How to check if a string is blank (empty, null, or contains only whitespace) in Kotlin

1 Answer

0 votes
fun isBlankOrEmpty(str: String?): Boolean {
    // Check for null or empty string
    if (str.isNullOrEmpty()) {
        return true
    }

    // Check if the string contains only whitespace
    return str.all { it.isWhitespace() }
}

fun main() {
    val testCases = listOf(null, "", "   ", "abc")

    testCases.forEachIndexed { index, test ->
        println("Test${index + 1}: ${isBlankOrEmpty(test)}")
    }
}

 
  
/*
run:
  
Test1: true
Test2: true
Test3: true
Test4: false

*/

 



answered Jun 8, 2025 by avibootz
...