Incerteza
Incerteza

Reputation: 34884

Check if a string is empty or blank

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?

Upvotes: 58

Views: 59180

Answers (4)

trozen
trozen

Reputation: 1273

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

Upvotes: 45

Gerstmann
Gerstmann

Reputation: 5518

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)

Upvotes: 90

Masklinn
Masklinn

Reputation: 61

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

Upvotes: 6

Thomas Ayoub
Thomas Ayoub

Reputation: 29441

Found in the doc :

impl Collection for String
    fn len(&self) -> uint
    fn is_empty(&self) -> bool

Upvotes: 1

Related Questions