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?
Asked
Active
Viewed 2.8k times
39
-
Use `\s+` replace with nothing. `inclusion of the 'regex' crate, ...` – Jul 16 '19 at 19:00
-
5I think this is a good question. This isn't a duplicate (closest is https://stackoverflow.com/q/37792471/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. – Justin Jul 16 '19 at 19:55
-
@Justin 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 https://stackoverflow.com/questions/37792471/removing-elements-from-a-vec-based-on-some-condition. – Stargateur Jul 16 '19 at 21:00
-
1@Justin We usually expect a greater amount of research before asking. For one, searching the standard library alone for [`replace`](https://doc.rust-lang.org/std/?search=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. – E_net4 Jul 16 '19 at 21:17
-
4@Stargateur 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. – Justin Jul 16 '19 at 21:30
-
2@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](https://stackoverflow.com/q/6219454/1896169) 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. – Justin Jul 16 '19 at 21:33
-
2@Stargateur 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 exist – Magix Jul 16 '19 at 21:34
5 Answers
50
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()
}
22
A good option is to use split_whitespace
and then collect to a string:
fn remove_whitespace(s: &str) -> String {
s.split_whitespace().collect()
}

Peter Mortensen
- 30,738
- 21
- 105
- 131

Magix
- 4,989
- 7
- 26
- 50
-
3@Magix `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. – E_net4 Jul 17 '19 at 08:12
-
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=6b86c8a9cb6138c0d554110c3e1c3822 – hellow Jul 17 '19 at 08:43
4
Actually I found a shorter approach
fn no_space(x : String) -> String{
x.replace(" ", "")
}

Jurij Jazdanov
- 1,248
- 8
- 11
-
7Nice ! 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()` – Magix Jan 05 '21 at 16:43
-
Initially I thought, we should use single quotes. Isn't whitespace a character ? – sreenivas Oct 05 '21 at 09:45
-
@sreenivas the replace function replaces not a single character but rather a string within another string, so here we use double quotes – frogstair Jul 31 '22 at 14:09
3
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.

Chayim Friedman
- 47,971
- 5
- 48
- 77
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

Saurabh
- 5,176
- 4
- 32
- 46