- split_whitespace
Remove extra whitespace from string
- 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.
examples/strings/remove-extra-white-spaces/src/main.rs
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'