56

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 4

85

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)
4
  • 1
    The "".to_string() version is an unnecessary String allocation.
    – pyrho
    Commented Oct 28, 2014 at 10:43
  • 16
    @pyrho I believe that the intention was to show that both &str and String have the is_empty() method. Commented Oct 28, 2014 at 10:44
  • 1
    I guessed so, I was just pointing out that it was bad practice (:
    – pyrho
    Commented Oct 28, 2014 at 11:35
  • 10
    FYI, "".to_string() does not cause an allocation (at least in current Rust). It translates to a RawVec::with_capacity(0), which does not allocate, as per Rust source code doc.rust-lang.org/src/alloc/raw_vec.rs.html#94-96.
    – U007D
    Commented Jun 29, 2018 at 21:11
41

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).

1
  • 7
    I expected this would not perform well, but then I looked at the source. Good answer! Commented Oct 26, 2019 at 19:13
5

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

1
  • It seems to be a unstable external crate, is there any other workaround? Commented Aug 6, 2017 at 16:08
1

Found in the doc :

impl Collection for String
    fn len(&self) -> uint
    fn is_empty(&self) -> bool
7
  • @AlexanderSupertramp what else ? Commented Oct 28, 2014 at 10:05
  • what about what else?
    – Incerteza
    Commented Oct 28, 2014 at 10:06
  • @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 literally unit. Commented Oct 29, 2014 at 1:34
  • @FrancisGagné, unit is written as unit, the value of unit is ().
    – Incerteza
    Commented Oct 29, 2014 at 4:20

Not the answer you're looking for? Browse other questions tagged or ask your own question.