Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string is empty or blank

Tags:

rust

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?

like image 679
Incerteza Avatar asked Oct 28 '14 09:10

Incerteza


2 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) 
like image 170
Gerstmann Avatar answered Oct 11 '22 19:10

Gerstmann


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

like image 39
trozen Avatar answered Oct 11 '22 19:10

trozen