Home » rust » Rust: Check if a string is empty

Rust: Check if a string is empty

Introduction

Rust is a powerful programming language that provides several ways to check if a string is empty. In this tutorial, we will explore three different methods for checking if a string is empty in Rust: the len() method, the is_empty() method, and the trim().is_empty() method. Each method has its own advantages and disadvantages, and we will provide examples of how to use each method. By the end of this tutorial, you will have a solid understanding of how to check if a string is empty in Rust and be able to choose the best method for your use case.

Check if a string is empty in Rust Examples

Using len()

The most straightforward way to check if a string is empty is to use the len() method. This method returns the number of characters in the string, and if the string is empty, the length will be 0.

fn main() {
    let s = "";
    if s.len() == 0 {
        println!("String is empty");
    } else {
        println!("String is not empty");
    }
}

Using is_empty()

Another way to check if a string is empty is to use the is_empty() method. This method returns a bool indicating whether the string is empty or not.

fn main() {
    let s = "";
    if s.is_empty() {
        println!("String is empty");
    } else {
        println!("String is not empty");
    }
}

Using trim().is_empty()

If you want to check if a string is empty after removing leading and trailing white spaces, you can use the trim().is_empty() method. This method first removes leading and trailing white spaces, then check if the string is empty.

fn main() {
    let s = "   ";
    if s.trim().is_empty() {
        println!("String is empty");
    } else {
        println!("String is not empty");
    }
}

Conclusion

In this tutorial, we have looked at three different ways to check if a string is empty in Rust, including using the len() method, the is_empty() method, and the trim().is_empty() method. Each method has its own advantages and disadvantages and you should choose the one that best fits your use case. It is important to note that all the above examples will only check for empty string, if you want to check for None or Null value, you need to use Option or Result type in rust.

Related: