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?
Remove all whitespace from a string
Asked Answered
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()
}
@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
Actually I found a shorter approach
fn no_space(x : String) -> String{
x.replace(" ", "")
}
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 quotes –
Ciliolate
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.
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
© 2022 - 2024 — McMap. All rights reserved.
\s+
replace with nothing.inclusion of the 'regex' crate, ...
– Zoireplace
returnsstd::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