Remove all whitespace from a string
Asked Answered
A

5

43

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?

Aenneea answered 16/7, 2019 at 18:55 Comment(7)
Use \s+ replace with nothing. inclusion of the 'regex' crate, ...Zoi
I think this is a good question. This isn't a duplicate (closest is https://mcmap.net/q/390605/-removing-elements-from-a-vec-based-on-some-condition-duplicate/1896169 , which you could argue this is a duplicate of, but it's clearly hard to find this one if you search for terms in this question), and at the least, it is a clear, concrete problem. Also, this is definitely not "too broad." It's a very clear defined problem, and a single problem.Chantey
@Chantey Still look like code request, this is a trivial question, any basic search would have answer this, I think we could even close as duplicate #37792971.Demerit
@Chantey We usually expect a greater amount of research before asking. For one, searching the standard library alone for replace returns std::str::replace as the third entry, which would have also done the job well. This is the kind of question that may well become useful, but will just have to prove its own usefulness with time.Dextrogyrate
@Demerit I very much disagree. Basic searches for removing whitespace from a string, erasing whitespace from a string, etc, don't turn up anything useful for Rust. You get other highly upvoted things for other languages, but not for Rust.Chantey
@E_net4isoutofcommentflags I have to disagree. How would you know to search for "replace"? This operation isn't obviously a replace; it's an erase/removal. When I did the basic research for this question, I found this highly upvoted C# question which is practically the same thing. The only way I was able to turn up useful results for Rust was by having the knowledge on what terms to remove from the search and what similar things to search for---at that level, a new Stack Overflow question is entirely appropriate.Chantey
@Demerit I searched before asking, and I asked specifically because there was no good, well-defined answer for Rust. Also, I believe over time this question could become a comparison between the different methods if many good answers existAenneea
P
52

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()
}
Pam answered 16/7, 2019 at 19:8 Comment(0)
A
23

A good option is to use split_whitespace and then collect to a string:

fn remove_whitespace(s: &str) -> String {
    s.split_whitespace().collect()
}
Aenneea answered 17/7, 2019 at 1:13 Comment(2)
@Aenneea split_whitespace does not consume the string, so making the function receive a string slice is the right thing to do. collect will create a String from the iterator of characters, but this will be the only allocation either way.Dextrogyrate
play.rust-lang.org/…Usa
F
4

Actually I found a shorter approach

fn no_space(x : String) -> String{
  x.replace(" ", "")
}
Fourier answered 1/1, 2021 at 0:15 Comment(3)
Nice ! This only works with normal space characters, though. In practice, there is a number of whitespace characters that one would want to remove, which are found using is_whitespace()Aenneea
Initially I thought, we should use single quotes. Isn't whitespace a character ?Courier
@Courier the replace function replaces not a single character but rather a string within another string, so here we use double quotesCiliolate
L
4

If you use nightly, you can use remove_matches():

#![feature(string_remove_matches)]

fn remove_whitespace(s: &mut String) {
    s.remove_matches(char::is_whitespace);
}

Somewhat surprisingly, it was found consistently faster than retain() in the (very imprecise) little benchmark I made.

Lefthanded answered 13/7, 2022 at 3:55 Comment(0)
Y
1

You can use trim() to remove whitespaces - space, tabs, and newline characters.

fn remove_space(data: &str) {
    for word in data.split(",") {
        println!("{:?}", word.trim());
    }
}

Here's the complete example on the playground

Yangyangtze answered 22/11, 2022 at 20:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.