What's the proper way to check if a string is empty or blank for a) &str b) String? I used to do it by "aaa".len() == 0
, but there should another way as my gut tells me?
Both &str
and String
have a method called is_empty
:
This is how they are used:
assert_eq!("".is_empty(), true); // a) assert_eq!(String::new().is_empty(), true); // b)
Empty or whitespace only string can be checked with:
s.trim().is_empty()
where trim()
returns a slice with whitespace characters removed from beginning and end of the string (https://doc.rust-lang.org/stable/std/primitive.str.html#method.trim).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With