Remove all whitespace from string

Magix picture Magix · Jul 16, 2019 · Viewed 8.8k times · Source

How do I remove all whitespace from a string? I can think of some obvious methods such as looping over the string and removing each whitespace character, or using regular expressions, but these solutions are not that expressive or efficient. What is a simple and efficient way to remove all whitespace from a string?

Answer

JayDepp picture JayDepp · Jul 16, 2019

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()
}