Remove all whitespace from string
If you want to modify the String
, use retain
. This is likely the fastest way when available.
fn remove_whitespace(s: &mut String) {
s.retain(|c| !c.is_whitespace());
}
If you cannot modify it because you still need it or only have a &str
, then you can use filter and create a new String
. This will, of course, have to allocate to make the String
.
fn remove_whitespace(s: &str) -> String {
s.chars().filter(|c| !c.is_whitespace()).collect()
}
A good option is to use split_whitespace
and then collect to a string :
fn remove_whitespace(s: &str) -> String {
s.split_whitespace().collect()
}