Remove extra whitespace from string
-
split_whitespace
-
The second solution is obviously the better solution, but the first one might be applied to situations where we would like to get rid of other duplicate characters.
fn main() {
let text = " Some white \n \n \n spaces \ntext \t \n with tabs \n";
println!("'{}'", text);
let short = text
.replace(['\n', '\t'], " ")
.trim()
.split(' ')
.filter(|short| !short.is_empty())
.collect::<Vec<_>>()
.join(" ");
println!("'{}'", short);
let other = text.split_whitespace().collect::<Vec<_>>().join(" ");
println!("'{}'", other);
}
' Some white
spaces
text
with tabs
'
'Some white spaces text with tabs'
'Some white spaces text with tabs'