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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A single boolean flag turns a stream of characters into a tiny state machine that dedupes runs.
- 2Pre-sizing a String with with_capacity avoids repeated reallocation during the build.
- 3Deferring edge trimming to the end keeps the main loop simple and uniform.
Related explainers
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/collapsing-runs-of-whitespace-in-rust-explained-rust-caaf/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.