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?
4 Answers
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)
-
1The "".to_string() version is an unnecessary String allocation.– pyrhoCommented Oct 28, 2014 at 10:43
-
16@pyrho I believe that the intention was to show that both
&str
andString
have theis_empty()
method. Commented Oct 28, 2014 at 10:44 -
1I guessed so, I was just pointing out that it was bad practice (:– pyrhoCommented Oct 28, 2014 at 11:35
-
10FYI,
"".to_string()
does not cause an allocation (at least in current Rust). It translates to aRawVec::with_capacity(0)
, which does not allocate, as per Rust source code doc.rust-lang.org/src/alloc/raw_vec.rs.html#94-96.– U007DCommented Jun 29, 2018 at 21:11
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).
-
7I expected this would not perform well, but then I looked at the source. Good answer! Commented Oct 26, 2019 at 19:13
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
-
It seems to be a unstable external crate, is there any other workaround? Commented Aug 6, 2017 at 16:08
Found in the doc :
impl Collection for String
fn len(&self) -> uint
fn is_empty(&self) -> bool
-
-
-
@AlexanderSupertramp Oh I misread you, sorry. as length can't be negative, it returns an unsigned int Commented Oct 28, 2014 at 10:07
-
@AlexanderSupertramp: In the language, unit is written
()
, not literallyunit
. Commented Oct 29, 2014 at 1:34 -
@FrancisGagné, unit is written as unit, the value of unit is (). Commented Oct 29, 2014 at 4:20