String.length / String.isEmpty()
Kotlin strings are of type String. They provide the length property to get the string length, and methods such as isEmpty() and isBlank() to check whether a string is empty or contains only whitespace.
Syntax
// String length val len: Int = string.length // Empty checks val empty: Boolean = string.isEmpty() // true when length is 0 val blank: Boolean = string.isBlank() // true when empty or whitespace only val notEmpty: Boolean = string.isNotEmpty() val notBlank: Boolean = string.isNotBlank()
Method List
| Method / Property | Description |
|---|---|
| string.length | Returns the number of characters in the string. |
| string.isEmpty() | Returns true if the string is empty (length is 0). |
| string.isNotEmpty() | Returns true if the string is not empty. |
| string.isBlank() | Returns true if the string is empty or contains only whitespace characters (spaces, tabs, newlines). |
| string.isNotBlank() | Returns true if the string is not blank (not whitespace only). |
| string.count() | Returns the number of characters matching a condition (filterable with a lambda). |
Sample Code
fun main() {
val s1 = "Hello, Kotlin!"
val s2 = ""
val s3 = " "
// Get the character count using length.
println(s1.length) // 14
println(s2.length) // 0
println(s3.length) // 3
// isEmpty / isNotEmpty
println(s1.isEmpty()) // false
println(s2.isEmpty()) // true
println(s1.isNotEmpty()) // true
// isBlank / isNotBlank (whitespace-only strings are also considered blank)
println(s2.isBlank()) // true
println(s3.isBlank()) // true (spaces only)
println(s1.isBlank()) // false
// Count characters matching a condition using count.
val vowelCount = s1.count { it in "aeiouAEIOU" }
println(vowelCount) // 3 (e, o, i)
// Example: checking user input for blank
val input = " "
if (input.isBlank()) {
println("Input is empty") // Input is empty
}
}
Notes
length is a property, so you do not need parentheses to access it. Note that this differs from Java's length() method.
isEmpty() and isBlank() behave differently: for a string containing only spaces or tabs, isEmpty() returns false while isBlank() returns true. For form input validation, it is generally recommended to use isBlank().
For extracting substrings, see string.substring() / drop() / take(). For splitting and joining strings, see string.split() / joinToString().
If you find any errors or copyright issues, please contact us.