Search code examples
regexrustwhitespaceremoving-whitespace

Remove all whitespace from a string


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


Solution

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