Sling Academy
Home/Kotlin/Checking if a String is Empty or Blank in Kotlin

Checking if a String is Empty or Blank in Kotlin

Last updated: December 04, 2024

In Kotlin, checking if a string is empty or consists solely of whitespace is a routine task, which often pops up when processing input or handling data entry forms. This article will walk you through the methods to efficiently check for empty or blank strings in Kotlin, complete with examples to illustrate each approach.

Basic Definitions

Before diving into the methods, it's crucial to define what we mean by an empty and blank string:

  • An empty string: A string with length == 0, denoted by "".
  • A blank string: A string that may include spaces, tabs, or other whitespace, such as " " or " \t".

Method 1: Using isEmpty()

The isEmpty() function checks if a string has zero length. Here’s a basic example:


fun checkEmptyString(input: String) {
    if (input.isEmpty()) {
        println("String is empty.")
    } else {
        println("String is not empty.")
    }
}

fun main() {
    checkEmptyString("")      // Outputs: String is empty.
    checkEmptyString("Kotlin") // Outputs: String is not empty.
}

Notice that isEmpty() will not consider strings with whitespace as empty.

Method 2: Using isBlank()

The isBlank() function goes a step further by checking if the string is either empty or contains only whitespace. Here's how it works:


fun checkBlankString(input: String) {
    if (input.isBlank()) {
        println("String is blank.")
    } else {
        println("String is not blank.")
    }
}

fun main() {
    checkBlankString("")          // Outputs: String is blank.
    checkBlankString("   ")       // Outputs: String is blank.
    checkBlankString("Kotlin")    // Outputs: String is not blank.
}

This method is particularly useful when dealing with user input forms, where the distinction between empty and blank can be important.

Method 3: Using custom functions

In some specific cases, you might need a tailored approach to define what 'blankness' means. Here’s how you could implement your own function:


fun isCompletelyEmpty(input: String?): Boolean {
    return input?.trim()?.isEmpty() ?: true
}

fun main() {
    println(isCompletelyEmpty(null))    // Outputs: true
    println(isCompletelyEmpty(""))     // Outputs: true
    println(isCompletelyEmpty(" "))    // Outputs: true
    println(isCompletelyEmpty("Kotlin")) // Outputs: false
}

This function checks if a string is null, empty, or blank by first trimming whitespace (using trim()) and utilizing safe calls (using ?. and Elvis operator ?:).

Conclusion

In Kotlin, you have versatile built-in options like isEmpty() and isBlank() to handle strings efficiently depending on your requirements. Whether it’s just a pilot check for empty strings or an in-depth scrutiny for white spaces, Kotlin's string utility functions empower you to process strings following a clean, readable syntax. Consider augmenting these methods with custom checks whenever dealing with nullable or complex requirements. Happy coding!

Next Article: Kotlin - Escaping Special Characters in Strings

Previous Article: Replacing Characters in Kotlin Strings

Series: Primitive data types in Kotlin

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin