Nurbol Alpysbayev
Nurbol Alpysbayev

Reputation: 21891

Is there a better way to test if a char is whitespace than converting it to a string?

I have a function that checks if a char is whitespace:

fn is_any_whitespace(ch: &char) -> bool {
    let re = Regex::new(r"\s").unwrap();
    let slice = &ch.to_string()[..];
    re.is_match(slice)
}

What bothers me is the part where I convert char to &str (&str is the type of the parameter that is_match accepts):

&ch.to_string()[..]

Can it be done more elegantly and efficiently?

Upvotes: 1

Views: 463

Answers (1)

SCappella
SCappella

Reputation: 10434

Instead of using regex for this problem, you can use char::is_whitespace. It should have the same behavior and will likely be more efficient, depending on compiler optimizations. In any case, not depending on the regex crate is a gain.

The only real difference is that char::is_whitespace takes self rather than &self. If you're worried about that, don't be. Using &char over char has no gain since char implements Copy. In fact, since chars are 4 bytes, it'll typically be more efficient to pass the characters directly, rather than an 8 byte pointer. And that's not even taking into account the extra layer of indirection.

If you insist on using the approach you have, it can be simplified to

use regex::Regex;

fn is_any_whitespace(ch: &char) -> bool {
    let re = Regex::new(r"\s").unwrap();
    re.is_match(&ch.to_string())
}

(playground)

Upvotes: 8

Related Questions