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.
string.is_empty()
string
: This is the string we want to check to see if it is empty or not.
The value returned is a Boolean value. A true
is returned if the string is actually empty. Otherwise, false
is returned.
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());}
In the above code:
is_empty()
method, and we check if each of the strings we created are empty. Then we print the result to the console.