How to check if a string is empty in Rust
Overview
We can check if a string is empty in Rust by using the is_empty() method. A string is empty if it has no character.
Syntax
string.is_empty()
Syntax for is_empty() method
Parameters
string: This is the string we want to check to see if it is empty or not.
Return value
The value returned is a Boolean value. A true is returned if the string is actually empty. Otherwise, false is returned.
Code
fn main() {// create some stringslet str1 = "Edpresso";let str2 = "";let str3 = "";let str4 = "Educative is the best platform!";// print the length of the stringsprintln!("{}", str1.is_empty());println!("{}", str2.is_empty());println!("{}", str3.is_empty());println!("{}", str4.is_empty());}
Explanation
In the above code:
- Lines 3–5: We create some strings, some of which are empty and some of which are not.
- Lines 9–12: We use the
is_empty()method, and we check if each of the strings we created are empty. Then we print the result to the console.