Check if a string is empty or blank
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).
Both &str
and String
have a method called is_empty
:
- Documentation for &str::is_empty
- Documentation for String::is_empty
This is how they are used:
assert_eq!("".is_empty(), true); // a)
assert_eq!(String::new().is_empty(), true); // b)
Others have responded that Collection.is_empty
can be used to know if a string is empty, but assuming by "is blank" you mean "is composed only of whitespace" then you want UnicodeStrSlice.is_whitespace()
, which will be true for both empty strings and strings composed solely of characters with the White_Space
unicode property set.
Only string slices implement UnicodeStrSlice
, so you'll have to use .as_slice()
if you're starting from a String
.
tl;dr: s.is_whitespace()
if s: &str
, s.as_slice().is_whitespace()
if s: String
Found in the doc :
impl Collection for String
fn len(&self) -> uint
fn is_empty(&self) -> bool