rust 18 lines · 5 steps

Collapsing runs of whitespace in Rust

A single pass with a boolean flag squeezes any run of whitespace down to one space.

Explained by highlit
1pub fn collapse_whitespace(input: &str) -> String {
2 let mut result = String::with_capacity(input.len());
3 let mut in_whitespace = false;
4 
5 for ch in input.chars() {
6 if ch.is_whitespace() {
7 if !in_whitespace {
8 result.push(' ');
9 in_whitespace = true;
10 }
11 } else {
12 result.push(ch);
13 in_whitespace = false;
14 }
15 }
16 
17 result.trim().to_string()
18}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A single boolean flag turns a stream of characters into a tiny state machine that dedupes runs.
  2. 2Pre-sizing a String with with_capacity avoids repeated reallocation during the build.
  3. 3Deferring edge trimming to the end keeps the main loop simple and uniform.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Collapsing runs of whitespace in Rust — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code